views:

186

answers:

3

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 interpretes this differently and why, but I would need to run two loop counters concurrently in a single for...?

Thanks, Sayan

+2  A: 

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

S.Mark
`zip` is good, but in this particular case, `enumerate` is the usual way of doing what the original poster wants.
EOL
+12  A: 

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.

Andrew Jaffe
+1, excellent !
S.Mark
Awesome, thanks!
Sayan Ghosh
+3  A: 
for i,j in enumerate(x)
ghostdog74