Difference between list comprehension and loops

Viewed 33
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?

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]
Related