Python: Nested Comprehensions

less than 1 minute read

You probably know how to rewrite a for loop such as:

lst = []
for j in s1:

as a comprehension:

lst = [j for j in s1]

But what about the following nested for loop?:

lst = []
for j in s1:
  for k in s2:
    lst.append((j, k))

Here you go:

lst = [(j, k) for j in s1 for k in s2]

Via StackOverflow.