Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does for x, *y in list mean in python

Tags:

python

list

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?

like image 699
Khachatur Mirijanyan Avatar asked Sep 05 '19 23:09

Khachatur Mirijanyan


People also ask

What does * in front of a list mean Python?

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.

What does * operator do Python list?

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.

What does X [:] mean in Python?

x[:] means the entire sequence. It's basically x[from:to] . Omitting from means, from the beginning until the to .

What does [:] mean in Python lists?

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.


2 Answers

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"]
like image 115
gtalarico Avatar answered Sep 22 '22 04:09

gtalarico


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]
like image 40
Sindhukumari P Avatar answered Sep 22 '22 04:09

Sindhukumari P