Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between list comprehension and loops

mag=[]
for i in nbn:
    for j in range(1,i+1):
        if i%j==0:
            mag.append(j)

It was a part of my code at the beginning, then for optimizing my code, I replaced it with another list comprehension, but it gives me a different output.

mag=[i for i in numbers_before_n  for j in range(1,i+1) if i%j==0]

What is the difference between these two types of loops?

like image 832
samira aslani Avatar asked Mar 08 '26 16:03

samira aslani


1 Answers

In your case list comprehension returns i but you want j:

mag=[j for i in numbers_before_n  for j in range(1,i+1) if i%j==0]
like image 142
dimay Avatar answered Mar 11 '26 04:03

dimay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!