Python for-loop in brackets vs parenthesis

Viewed 133

I just started some months ago learning python3. I was curious where the difference between the following code is and when to use it.


#A:
for i in [x*2 for x in range(100)]:
    if i == 2:
        break
#B:
for i in (x*2 for x in range(100)):
    if i == 2:
        break

So the first one(A) is in square brackets and the other one(B) is in "normal" brackets. Where is the difference between them, and which one is perferably better in this kind of case.

1 Answers

as said in the comments by jonrsharpe:

One's a list comprehension, the other a generator expression

But say you did do something inside the loop. The generator would be better since it wouldn't load all the number in at once. So, it uses less memory. At last, perhaps this question also answers your question.

Related