-2

I decided to start learning python from scratch using udemy, and my instructor gave an example which was too simple, so I wanted to make It more complex. However I did experience an error and I understand why I'm getting the error but don't know how to bypass it.

Here is the code in question:

mylist = [(1,2,3),(5,6,7),(8,9)]

for a,b,c in mylist:
    print(b)

the output will be 2 6 and then an error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-a5ddba3739a9> in <module>
      1 mylist = [(1,2,3),(5,6,7),(8,9)]
      2 
----> 3 for a,b,c in mylist:
      4     print(b)

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

Because the tuple is not the same as the first two the error occurs.

How can i fix such an issue if something similar happens in the future, because in theory It could happen and not only i can add different sized tuples in a list but other types as well.

Thanks

Edit:

Extended Unpacking was the solution, thank you everyone for the help.

Wishy
  • 15
  • 9
  • Your question doesn't clearly state your goal. What should it be? Always print the second value of any tuple in the list? Also, what should happen if it contains less than 2 items? Please clarify. – Thierry Lathuille Mar 14 '21 at 09:35
  • Use extended packing a,b,*c. – Ashish M J Mar 14 '21 at 09:36
  • Why not ask your course instructor? – TigerhawkT3 Mar 14 '21 at 09:42
  • @TigerhawkT3 i did ask the instructor but his assistant answered incorrectly and then ignored my reply, so i figured here would be the best place to ask. – Wishy Mar 14 '21 at 22:01
  • Extended unpacking was the answer @ThierryLathuille. I thought that my question was clear, and based on the answers provided so did the others. – Wishy Mar 14 '21 at 22:02

2 Answers2

3

In this particular case you can use extended unpacking

mylist = [(1,2,3),(5,6,7),(8,9)]

for a,b,*c in mylist:
    print(b)

where c will be list that holds all elements starting from index 2 to the end.

You can also check Unpacking, extended unpacking and nested extended unpacking

buran
  • 13,682
  • 10
  • 36
  • 61
1

You can put None in the list

>>li=[(1,2,3),(5,6,7),(8,9,None)]
>>> for a,b,c in li:
...     print(b)
Peter Badida
  • 11,310
  • 10
  • 44
  • 90