Search code examples
pythonlist-comprehensionnested-loops

How to nested loop in list comprehension


I have a piece of code down here, and I'm wondering if I can make this simpler with list comprehension in Python...

T: str = 'XY'
combinations: list = [] # Make an empty list

for i in range(len(T)):
    for j in range(len(T)): combinations.append((T[i], T[j])) # (T[i], T[j]) is act as a tuple here

How can I simplify this into a better for loop without taking so many times to loop around i and j? Much help is appreciated :)


Solution

  • If you are interested in List-comprehension version of the code you have written:

    >>> [(T[i], T[j]) for j in range(len(T)) for i in range(len(T))]
    [('X', 'X'), ('Y', 'X'), ('X', 'Y'), ('Y', 'Y')]
    

    Modified List-comprehension without len and range, but iterating the string itself:

    >>> [(x,y) for x in T for y in T]
    [('X', 'X'), ('X', 'Y'), ('Y', 'X'), ('Y', 'Y')]
    

    If you want to use product function standard library itertools:

    >>> from itertools import product
    >>> list(product(T, repeat=2))
    [('X', 'X'), ('X', 'Y'), ('Y', 'X'), ('Y', 'Y')]