Assign multiple values of a list

Simply type it out:

>>> a,b,c,d = [1,2,3,4]
>>> a
1
>>> b
2
>>> c
3
>>> d
4

Python employs assignment unpacking when you have an iterable being assigned to multiple variables like above.

In Python3.x this has been extended, as you can also unpack to a number of variables that is less than the length of the iterable using the star operator:

>>> a,b,*c = [1,2,3,4]
>>> a
1
>>> b
2
>>> c
[3, 4]

Totally agree with NDevox's answer

a,b,c,d = [1,2,3,4]

I think it is also worth to mention that if you only need part of the list e.g only the second and last element from the list, you could do

_, a, _, b = [1,2,3,4]

a, b, c, d = myList is what you want.

Basically, the function returns a tuple, which is similar to a list - because it is an iterable.

This works with all iterables btw. And you need to know the length of the iterable when using it.

Tags:

Python

List