Reputation: 6485
I have a nested for loop and I'd like to convert it to a list comprehension in python. How can I do that
all_combinations = []
for i in range(0,size):
for j in range(i,size):
if i!=j:
all_combinations.append((i,j))
Upvotes: 0
Views: 88
Reputation: 8222
Why not just
all_combinations = [(i,j) for i in range(size) for j in range(i+1,size) ]
Don't need an if test because this will never include (i,i)
Upvotes: 1
Reputation: 81684
All the other answers answer your question, but I'd like to suggest a better alternative, itertools.combinations
:
from itertools import combinations
print(list(combinations(range(3), 2)))
# [(0, 1), (0, 2), (1, 2)]
Why is it better?
range(3)
only once.Upvotes: 3
Reputation: 8273
all_combinations = [(i,j) for i in range(size) for j in range(i,size) if i!=j]
Upvotes: 2
Reputation: 51725
List comprehension:
all_combinations = [ (i,j) for i in range(0,size) for j in range(i,size) if i!=j ]
Upvotes: 1