Search code examples
pythonlisttuplesenumerateunpack

How to unpack a tuple of lists


I am attempting to unpack the elements of a list that is packed inside a tuple.

myTuple = (['a', 'list', 'of', 'strings'], ['inside', 'a', 'tuple'], ['extra', 'words', 'for', 'filler'])

So for example I want to get this element ('a')

I have tried this:

for (i, words) in list(enumerate(myTuple)):
    print(words)

But this returns the list like this

['a', 'list', 'of', 'strings']
['inside', 'a', 'tuple']
etc...

How can I get the elements inside the list?


Solution

  • You can use the indexing of your tuple and then the lists to access the inner-most elements. For example, to get at the string 'a', you could call:

    myTuple[0][0]
    

    If you wanted to iterate over all the elements in the lists, you could use the chain method form itertools. For example:

    from itertools import chain
    
    for i in chain(*myTuple):
        print(i)