Search code examples
pythonlist-comprehension

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:

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