codeKiller
codeKiller

Reputation: 5758

Assign multiple values of a list

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)

So that:

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]

Upvotes: 31

Views: 41699

Answers (5)

Buddy Bob
Buddy Bob

Reputation: 5889

You can also use a dictionary. This was if you have more elements in a list, you don't have to waste time hardcoding that.

import string
arr = [1,2,3,4,5,6,7,8,9,10]
var = {let:num for num,let in zip(arr,string.ascii_lowercase)}

Now we can access variables in this dictionary like so.

var['a']

Upvotes: 0

AbdealiLoKo
AbdealiLoKo

Reputation: 3357

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.

Upvotes: 6

One trick is to use the walrus operator in Python 3.8 so that you still have the my_list variable. And make it a one-line operation.

>>> my_list = [a:=3, b:=5, c:=7, d:=2]
>>> a
3
>>> b
5
>>> c
7
>>> d
2
>>> my_list
[3, 5, 7, 2]

PS: Using camelCase (myList) is not pythonic too.

What's new in Python 3.8 : https://docs.python.org/3/whatsnew/3.8.html

Upvotes: 5

r0n9
r0n9

Reputation: 2759

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]

Upvotes: 11

NDevox
NDevox

Reputation: 4086

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]

Upvotes: 49

Related Questions