简体   繁体   中英

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.

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.

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM