grokpot
grokpot

Reputation: 1492

Python: performance of for loops over a list comprehension

In the instance where I iterate a list comprehension via a for-loop:
Is the list comprehension cached when the for loop is executed, or is the list re-generated on every execution?

In other words, would these two examples perform differently?

for x in [list comprehension]  

vs

list_comprehension = [list comprehension]
for x in list_comprehension

I could use an iterator, which I believe uses a generator, but I'm just curious about the Python for-loop execution here.

Upvotes: 1

Views: 129

Answers (3)

Kasravnd
Kasravnd

Reputation: 107287

with this command : list_comprehension = [list comprehension] actually you create another pointer to that part of memory that array have been saved !

So the for loop is same in tow case ! see this Demo:

>>> a=[1,2,4]
>>> b=a
>>> b
[1, 2, 4]
>>> a
[1, 2, 4]
>>> a.append(7)
>>> a
[1, 2, 4, 7]
>>> b
[1, 2, 4, 7]

Upvotes: 0

tdelaney
tdelaney

Reputation: 77347

When you do

for x in [list comprehension]:

the entire list is built before the for loop starts. Its basically equivalent to the second example except for the variable assignment.

Upvotes: 3

trvrm
trvrm

Reputation: 814

a list comprehension returns a list. The only difference between your two examples is that you're binding the output list to a variable in the second.

A generator expression returns an iterator, which means that:

  • It won't get evaluated until you use it
  • If you want to use it more than once you'll have to generate it each time.

Upvotes: 2

Related Questions