0

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?

3
  • Side-note: Don't name your variable list (or any other built-in name). That's just asking for trouble. My answer used mylist as a safe placeholder. Commented Nov 11, 2015 at 9:16
  • another side-note: rather than stating that "there is an error" it can often be quite helpful to post that error. Commented Nov 11, 2015 at 9:20
  • Overwriting the name of a standard-type makes it unreachable for other calls. Do not! Commented Nov 11, 2015 at 10:28

2 Answers 2

6

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.

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

1 Comment

FYI, I followed the convention of i and j referring to indices, while x and y refer to values. Your original question uses i and j for the values, which will trip up maintainers. Obviously, meaningful names are best (and i and j might be better made ix and iy to indicate the index relationship with x and y), but for example code, I'll stick with conventional one-letter names.
3

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

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.