How can list comprehension loops be nested?

is this possible to create a nested loop in list comprehensions ?

Yes it is, and there are a variety of configurations.

def powers(bases, exponents):
    return [a ** x for a in bases for x in exponents]

Pass in two lists, one of bases and the other of exponents and the above returns a list of each base raised to all exponents.

It is also possible to operate on the outcome of one comprehension nested in another comprehension.

[x for x in [y for y in data]]

where data is a sequence.

41 Likes

Ohhh really thanks for making it clear :smiling_face_with_three_hearts:
idk why i love list comprehensions too much :heart_eyes::heart_eyes: .

6 Likes

Hi, when I practiced this task, this was what I wrote:

def exponents(bases, powers):
new_lst =
for base in bases:
power = [base**power for power in powers]
new_lst.append(power)
return new_lst

it results in three lists:
[[2, 4, 8], [3, 9, 27], [4, 16, 64]]

However, the answer is
[2, 4, 8, 3, 9, 27, 4, 16, 64]
which is just one list, combining together
the answer code is :

def exponents(bases, powers):
new_lst =
for base in bases:
power = [base**power for power in powers]
new_lst.append(power)
return new_lst

I still can’t figure out why make mine and the result of the standard answer code different.
If anyone can tell me why I would be grateful!

That is creating a separate list which ends up being appended to the new list, as a list

[ [...], [...], [...] ]

when it should be a single, flattened list in the return.

[ ... ]
    for base in bases:
        for power in powers:
            new_lst.append(base ** power])

Since you are endeavoring to implement list comprehension what happens if we nest both in a single list?

>>> def exponents(bases, powers):
	return [a ** x for a in bases for x in powers]

>>> exponents([2, 3, 4], [1, 2, 3])
[2, 4, 8, 3, 9, 27, 4, 16, 64]
>>> 
9 Likes

Thank you so much mtf.
Your code is amazingly beautiful and concise.

2 Likes

Hello Mtf,
Sorry for bothering, can you please elaborate on the second code(I could not catch the idea, If it is possible please provide an example)
Thanks is advance

[x for x in [y for y in data]]

I edited the above to include assignment to a variable, e. We could write the above in two parts.

d = [y for y in data]

and then,

e = [x for x in d]

The combined example replaces d with [y for y in data]. The inner comprehension is derived from data, first, then the outer comprehension is derived from the list generated in the inner comprehension.

2 Likes

Thank you very much for your prompt response.
So as I understand it is a nested comprehension loop and in place of data we can put list,range or any sort of data?

Yes, data can be any iterable object, a range, a map, a filter, a list, a tuple, a set, a str, or even a dict.

[ expression_of_x for x in iterable ]
1 Like

Thanks a lot again, this helped me so much!)

1 Like

I have this code :

numbers = [1,2,3,4,5,6,7,8,9]
for num in numbers:
even =
odd =
if num % 2 == 0:
even.append(num)
elif num % 2 >= 1:
odd.append(num)

counted_even = len(even)
counted_odd = len(odd)

print(counted_even)
print(counted_odd)

It is supposed to print out the amount of even and odd numbers from the list “numbers” but it’s not working.

My output is 0, 1, 1, 0 , 1, 1, 1 ,0

I keep getting this same error everytime I try to implement an if statement in a for loop.

Can someone please help me here?

numbers = [1,2,3,4,5,6,7,8,9]
for num in numbers:
even =
odd =
if num % 2 == 0:
even.append(num)
elif num % 2 >= 1:
odd.append(num)

counted_even = len(even)
counted_odd = len(odd)

print(counted_even)
print(counted_odd)

Also, with this code, I only get 0 and 1 as my output when I am supposed to get 5 and 4. What did I do wrong here?

Parity is binary, which means a number is either odd or even. There is no remainder greater than 1; but, neither is there a need for an elif.

What would I put instead of the elif then?

If it is not even then it must be odd. else comes to mind.

alright thank you and just to make sure, the variables and everything is in the right place right?

Everything should work now.

It does. Thank you !

I still don’t understand this…what is data for example in out case of exponents(bases,powers), what should i used in place of data… exponents, bases or powers.? How it would iterate…
[x for x in [y for y in data]]… :confused: