HHH
HHH

Reputation: 6485

How to convert a for loop to a list comprehension in python

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

Answers (4)

nigel222
nigel222

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

DeepSpace
DeepSpace

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?

  • There is no repetition. We specify range(3) only once.
  • It is tested, standard library code.
  • Shorter and more readable.
  • (If using CPython, which you probably are) It is implemented in C which means it is (usually) faster than nested Python loops.

Upvotes: 3

mad_
mad_

Reputation: 8273

all_combinations = [(i,j)  for i in range(size) for j in range(i,size) if i!=j]

Upvotes: 2

dani herrera
dani herrera

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

Related Questions