user1220022
user1220022

Reputation: 12105

python list iteration

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?

Upvotes: 3

Views: 927

Answers (2)

Daemoneye
Daemoneye

Reputation: 117

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

Upvotes: 2

eumiro
eumiro

Reputation: 213125

Use itertools.permutations:

import itertools as it
for i, j in it.permutations(range(5), 2):
    print i, j

Upvotes: 10

Related Questions