Sayan Ghosh
Sayan Ghosh

Reputation: 261

Multiple counters in a single for loop : Python

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?

Upvotes: 24

Views: 75484

Answers (3)

YOU
YOU

Reputation: 123821

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

Upvotes: 23

ghostdog74
ghostdog74

Reputation: 342333

for i,j in enumerate(x)

Upvotes: 6

Andrew Jaffe
Andrew Jaffe

Reputation: 27077

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.

Upvotes: 35

Related Questions