0

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?

1
  • 1
    in first loop you do item1, item2 = "one" so you get error Commented Dec 2, 2015 at 1:13

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.