2

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.

LinFelix
  • 1,026
  • 1
  • 13
  • 23
izuso
  • 39
  • 2
  • 5
    One's a list comprehension, the other a generator expression. In this case they're both pointless, because you don't do anything inside the loop! – jonrsharpe Jan 03 '22 at 15:11

1 Answers1

0

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.

Robin Dillen
  • 704
  • 5
  • 11