Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested For Loops Using List Comprehension

If I had two strings, 'abc' and 'def', I could get all combinations of them using two for loops:

for j in s1:   for k in s2:     print(j, k) 

However, I would like to be able to do this using list comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this?

like image 609
John Howard Avatar asked Sep 03 '10 04:09

John Howard


People also ask

Can we use nested loop in list comprehension?

Example List comprehension nested for loop. Simple example code uses two for loops in list Comprehension and the final result would be a list of lists. we will not include the same numbers in each list. we will filter them using an if condition.

What is nested comprehension in Python?

List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.


2 Answers

lst = [j + k for j in s1 for k in s2] 

or

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

if you want tuples.

Like in the question, for j... is the outer loop, for k... is the inner loop.

Essentially, you can have as many independent 'for x in y' clauses as you want in a list comprehension just by sticking one after the other.

To make it more readable, use multiple lines:

lst = [        j + k         # result        for j in s1   # for loop           for k in s2 # for loop                      # condition           ] 
like image 192
aaronasterling Avatar answered Sep 29 '22 23:09

aaronasterling


Since this is essentially a Cartesian product, you can also use itertools.product. I think it's clearer, especially when you have more input iterables.

itertools.product('abc', 'def', 'ghi') 
like image 25
miles82 Avatar answered Sep 29 '22 21:09

miles82