The Python Argument Unpacking Operator(*)

This note is based on an answer I’ve given to one of my peers on an online course on data science. His question went something along the lines of:

What does *point in this snippet points = [Point(*point) for point in points] do?

The course has ended and the question-answer community website will soon be wiped clean for the next run of the course, so I thought I could write it down here as a future reference.

The * operator in Python unpacks a collection into positional arguments.
It’ll be clear with an example:
Let’s say we have, points = [(1,2),(3,4),(5,6)].
Now, if we want to print both first and second elements of each point we will normally do:

for point in points:
    print(point[0],point[1])

Using * we can do it simply as:

for point in points:
    print(*point)

Both will print the same value. So passing *point is equivalent to passing point[0],point[1]. This works for collections having any number of elements. For example, if a point is defined as point = (1,2,3) then print(*point) is equivalent to print(point[0],point[1],point[2])

So points = [Point(*point) for point in points] is equivalent to points = [Point(point[0],point[1]) for point in points]


programming
python