Unpacking a list into multiple variables

Question:

Is there a way to unpack a list of lists, but into multiple variables?

scores = [['S', 'R'], ['A', 'B'], ['X', 'Y'], ['P', 'Q']]

Into:

a = ['S', 'R'], b = ['A', 'B'], c = ['X', 'Y'], d = ['P', 'Q']

Seems like something that should be quite simple and yet I’m unable to find a solution that doesn’t involve extracting all the individual elements into one big list, which is not what I want to do. I want to retain the 4 individual objects, just not stored inside a list or dictionary.

Looking for a general solution that might apply if the number of lists within the list / number of variables change.

Asked By: Gonde94

||

Answers:

Generating variable programmatically is not a good idea, rather use a dictionary:

from string import ascii_lowercase

scores = [['S', 'R'], ['A', 'B'], ['X', 'Y'], ['P', 'Q']] 

dic = dict(zip(ascii_lowercase, scores))

NB. IMO it’s still better to keep the original list.

Output:

{'a': ['S', 'R'], 'b': ['A', 'B'], 'c': ['X', 'Y'], 'd': ['P', 'Q']}

Or, if you have a known number of lists, unpack them:

a, b, c, d = scores
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.