24

Is it possible in Python to run multiple counters in a single for loop as in C/C++?

I would want something like -- for i,j in x,range(0,len(x)): I know Python interprets this differently and why, but how would I run two loop counters concurrently in a single for loop?

1
  • 4
    Aside (since you probably don't want to use it in this case): range(0, len(x)) == range(len(x)) Commented Apr 20, 2010 at 6:23

3 Answers 3

35

You want zip in general, which combines two iterators, as @S.Mark says. But in this case enumerate does exactly what you need, which means you don't have to use range directly:

for j, i in enumerate(x):

Note that this gives the index of x first, so I've reversed j, i.

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

Comments

23

You might want to use zip

for i,j in zip(x,range(0,len(x))):

Example,

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> print zipped
[(1, 4), (2, 5), (3, 6)]
>>> for a,b in zipped:
...     print a,b
...
1 4
2 5
3 6
>>>

Note: The correct answer for this question is enumerate as other mentioned, zip is general option to have multiple items in a single loop

1 Comment

zip is good, but in this particular case, enumerate is the usual way of doing what the original poster wants.
6
for i,j in enumerate(x)

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.