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

extract tuple items from list without accessing index

I am trying to extract the tuple items which consist of another embedded tuple without using the index.

items = [(('a', 'b'), 'a'), (('a', 'b'), 'b'), (('a', 'b'), 'c'), (('a', 'b'), 'd')]

# Currently accessing using index
for xy,z in items:
    print(xy[0],xy[1],z)

# Trying without index but getting error
for x, y, z in items:
    print(x,y,z)

for item in items:
    x, y, z = item
    print(x,y,z)

Error:

ValueError: not enough values to unpack (expected 3, got 2)

Is it possible?

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

>Solution :

Yes, you just need to wrap the nested tuple to have an extra layer of unpacking:

for (x, y), z in items:
    print(x,y,z)

Note how (x, y) causes the inner tuple to be unpacked.

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