Reputation: 95
I've got a simple python question. First, see the code.
l1 = ['one', ['1', '2']]
for item1, item2 in l1:
print (item1)
for subitem in item2:
print (subitem)
I assumed that this would print 'one' then '1' '2', but I receive the error:
for item1, item2 in l1:
ValueError: too many values to unpack (expected 2)
There's some code in the tutorial that I'm following (https://automatetheboringstuff.com/chapter9/) that leads me to believe that what I'm trying to do (the multiple args with the in statement) is possible - but what is the logic here?
Upvotes: 0
Views: 193
Reputation: 280778
Your outer loop shouldn't be a loop:
item1, item2 = l1
print(item1)
for subitem in item2:
print(subitem)
A loop like for item1, item2 in l1
expects each element of l1
to unpack into two items separately. For example, if l1
were [(1, 2), (3, 4), ...]
, then the first iteration would set item1, item2 = 1, 2
, and the second iteration would set item1, item2 = 3, 4
, and so on.
Upvotes: 2