I am curious to know if there is a "pythonic" way to assign the values in a list to elements? To be clearer, I am asking for something like this:
myList = [3, 5, 7, 2] a, b, c, d = something(myList)
a = 3 b = 5 c = 7 d = 2
I am looking for any other, better option than doing this manually:
a = myList[0] b = myList[1] c = myList[2] d = myList[3]
42.1k 19 19 gold badges 115 115 silver badges 152 152 bronze badges
asked Jul 15, 2015 at 9:09
codeKiller codeKiller
5,690 19 19 gold badges 69 69 silver badges 127 127 bronze badges
'assing' != 'assign' , although that's a very amusing typo
Commented Jul 15, 2015 at 9:15
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]