Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python reuse lists if possible?

Tags:

python

What I mean is, if you over-write a list with a list of identical shape, does it keep the first list? For example:

point = [1, 2]
for x in xrange(10000000):
    point = [x, x + 1]

does python reuse the list from point = [1, 2] in each iteration of the loop, simply updating the references at point[0] and point[1] to x and x + 1? Or does it create a new list in each iteration and throw out the old one? Put another way, is that equivalent in performance to

point = [1, 2]
for x in xrange(10000000):
    point[0] = x
    point[1] = x + 1

I'm just curious if python does that type of optimization under the hood

Edit: In addition to what everyone said below, I benchmarked it for my own curiosity.

On my venerable thinkpad's Core2Duo:

point = [1, 2]
for x in xrange(10000000):
    point = [x, x + 1]

# Result:
# real    0m6.164s


point = [1, 2]
for x in xrange(10000000):
    point[0] = x
    point[1] = x + 1

# Result:
# real    0m3.623s
like image 998
Joe Pinsonault Avatar asked Dec 01 '22 16:12

Joe Pinsonault


1 Answers

No, CPython does not re-use list objects. The line point = [x, x + 1] creates an entirely new object, and the previous object is destroyed if point was the only reference.

Python does reuse tuple objects (up to a limit), because Python internals create and destroy a lot of tuples in the normal course of a Python program. See How is tuple implemented in CPython?

like image 51
Martijn Pieters Avatar answered Dec 17 '22 14:12

Martijn Pieters