user3397243
user3397243

Reputation: 567

Using for loop to iterate two variables together

How do I go about doing something like this?

Say I have an array x = np.array([1,2,3,4,5]) of length 5,

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

I want i and j to increment together.

This is throwing me an error message:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-37d0ddc3decf> in <module>()
----> 1 for i,j in range(len(x)):
      2     print i,j
      3 

TypeError: only length-1 arrays can be converted to Python scalars

The reason I need this is because I have to use it in a condition inside the for loop. Like say, y[i][j] and I want this to be 0,0 then 1,1 and so on.

Upvotes: 1

Views: 262

Answers (3)

Julien Spronck
Julien Spronck

Reputation: 15433

Why do you need j in the first place? If j is always equal to i, just use i. No need for a second variable.

Upvotes: 4

Anshul Goyal
Anshul Goyal

Reputation: 76997

Edited answer

OP says

The reason I need this is because I have to use it in a condition inside the for loop. Like say, y[i][j] and I want this to be 0,0 then 1,1 and so on.

In that case, you could simply use:

y[i][i]

Original answer

I'm not really sure why you would want to do that, you could just set it in the first line of the for loop:

for i in range(len(x)):
    j = i
    ... #rest of the code follows

You could also use enumerate, as pointed in comments by @Julien, like below (but IMO, the earlier method is better):

>>> for i, j in enumerate(xrange(len(x))):
...     print i, j
... 
0 0
1 1
2 2

Upvotes: 2

gus27
gus27

Reputation: 2656

You could try this:

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

So the question is about how to iterate two variables, not why ;-)

Upvotes: 1

Related Questions