I recently came across a piece of python code that looked like this
groups = {}
for d, *v in dishes:
for x in v:
groups.setdefault(x, []).append(d)
dishes represents a 2d array. What does the 1st for loop statement mean? What is *v? What does the asterisk before v indicate? What other situations is an asterisk before a variable used?
The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.
We can unpack list elements to comma-separated variables. Python List can have duplicate elements. They also allow None. List support two operators: + for concatenation and * for repeating the elements.
x[:] means the entire sequence. It's basically x[from:to] . Omitting from means, from the beginning until the to .
A shortcut way to copy a list or a string is to use the slice operator [:] . This will make a shallow copy of the original list keeping all object references the same in the copied list.
It's essentially a combination of tuple/list unpacking and *args
iterable unpacking. Each iterable is getting unpacked on each iteration of the for loop.
First let's look at a simple tuple/list unpacking:
>>> x, y = (1, 2)
>>> x
1
>>> y
2
# And now in the context of a loop:
>>> for x, y in [(1, 2), (3, 4)]:
>>> print(f'x={x}, y={y}')
"x=1, y=2"
"x=3, y=4"
Now consider the following (and imagine the same concept within the loop as shown above):
>>> x, y = (1, 2, 3)
ValueError: too many values to unpack (expected 2)
>>> x, *y = 1, 2, 3
>>> x
1
>>> y
[2, 3]
Note how *
allows y
to consume all remaining arguments.
This is similar to how you would use *
in a function - it allows an unspecified number of arguments and it consumes them all.
You can see more examples of (*args)
usage here.
>>> def foo(x, *args):
>>> print(x)
>>> print(args)
>>>foo(1, 2, 3, 4)
1
[2, 3, 4]
As for practical examples, here is a quick one:
>>> names = ("Jack", "Johnson", "Senior")
>>> fist_name, *surnames = names
>>> print(surnames)
["Johnson", "Senior"]
Basically * indicates n number of countless elements.
Example :
x=1,2,4,6,9,8
print(type(x))
print(x)
Output:
<class 'tuple'>
(1, 2, 4, 6, 9, 8)
y,*x=1,2,4,6,9,8
print(type(x))
print(x)
Output:
<class 'list'>
[2, 4, 6, 9, 8]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With