Jeril
Jeril

Reputation: 8531

Python - C program for loop equivalent

I was using the following for loop in my C program:

for (i = 0; i < 5; i++) {
  for (j = i + 1; j < 5; j++) {
    //some operation using the index values
  }
}

What would be the python equivalent for the second for loop, (j = i + 1)? I tried the following but there is an error:

for indexi, i in enumerate(list):
    for indexj = indexi + 1, j in enumerate(list):

How to do it?

Upvotes: 0

Views: 165

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155506

If you're trying to get the actual index values for some reason (and/or need to control the inner loop separate from the outer), you'd do:

for i in range(len(mylist)):
    for j in range(i+1, len(mylist)):

# Or for indices and elements:
for i, x in enumerate(mylist):
    for j, y in enumerate(mylist[i+1:], start=i+1):

But if what you really want is unique non-repeating pairings of the elements, there is a better way, itertools.combinations:

import itertools

for x, y in itertools.combinations(mylist, 2):

That gets the values, not the indices, but usually, that what you really wanted. If you really need indices too, you can mix with enumerate:

for (i, x), (j, y) in itertools.combinations(enumerate(mylist), 2):

Which gets the exact index pattern you're looking for, as well as the values. You can also use it to efficiently produce the indices alone as a single loop with:

for i, j in itertools.combinations(range(len(mylist)), 2):

Short answer: itertools is magical for stuff like this.

Upvotes: 6

Daniel Roseman
Daniel Roseman

Reputation: 599788

If you're really just interested in the indexes, you can use range rather than enumerate.

for i in range(5):
    for j in range(i+1, 5):
        print i, j

Upvotes: 3

Related Questions