3

I have a list iteration in python defined like this:

for i in range(5):
    for j in range(5):
        if i != j:
            print i , j

So for each element in my defined range [0..5] I want to get each element i, but also all other elements which are not i.

This code does exactly as I expect, but is there a cleaner way of doing this?

2
  • You could use range() only once before the two loops as a first level optimization Commented Mar 29, 2012 at 8:52
  • From an efficiency point of view, this is perfectly serviceable, unless you're calling it in a tight loop or significantly increasing 5, I wouldn't worry. From a legibility point of view, this is perfectly readable. Commented Mar 29, 2012 at 8:53

2 Answers 2

10

Use itertools.permutations:

import itertools as it
for i, j in it.permutations(range(5), 2):
    print i, j
Sign up to request clarification or add additional context in comments.

1 Comment

However, the OP's code is very easy to understand without requiring the reader to know itertools; itertools shines when you need to scale these to more dimensions or need it more than once.
2

[(x,y)for x in range(5) for y in range(5) if x!=y]

1 Comment

Please provide more information in your answers. Some background or explanations for posterity is recommended.

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.