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?
>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.