Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unpacking a list into multiple variables

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

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

Into:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading