0

I have learned about the working of for loop and all. I decided to pass a double value inside the for loop. The code looks like:

name = 'dfsdf'
for index,string in name:
    print index

When I run the code it give me error like

ValueError: need more than 1 value to unpack

When I have added a single value it works just fine. Why does it throws an error when I used two names? Can double values be passed with for statement in python?

1 Answer 1

1

Can double values be passed with for statement in python?

Yes, but the sequence you're iterating over must contain elements which themselves contain two elements apiece. For example, [(1,2),(3,4),(5,6)]. Ordinary strings don't fit the bill, but the return value of enumerate does.

>>> name = 'dfsdf'
>>> for index,string in enumerate(name):
...     print index
...
0
1
2
3
4

>>> for a,b in [(1,2),(3,4),(5,6)]:
...     print a
...
1
3
5
Sign up to request clarification or add additional context in comments.

1 Comment

for index, string in [(1,2), (3,4), (5,6)]: The for loop iterates over the list of tuples, and on each iteration a tuple is unpacked into index and string.

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.