Is python reuse lists possible?

What do I mean if you rewrite a list with a list of the same form, will it keep the first list? For instance:

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

Does python use a list of from point = [1, 2]in each iteration of the loop, just updating the links in point[0]and point[1]to xand x + 1? Or does he create a new list at each iteration and throw away the old one? In other words, this is the equivalent of performance

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

I'm just wondering if python does this type of optimization under the hood

Edit: In addition to what everyone said below, I compared it out of my own curiosity.

On my venerable thinkpad 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
+4
source share
5 answers

, CPython . point = [x, x + 1] , , point .

Python tuple ( ), Python Python. . CPython?

+6

print, :

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

point , , .

+4

. point = [1, 2], , , , Python [1, 2] point . point = [x, x+1], Python , point . [1, 2] STILL IN-, Python . :

point = [1, 2]
b = point
point = [3, 4]
print(b == point)

point2= [1, 2]
c = point2
point2[0] = 3
print(c == point2)

.

+3

, python : point = [x,x+1], , , .

:

point = [1,2]

for x in range(5): # Reusing point list
    point[:] = [x,x+1]

for x in range(5): # Creating new list
    point = [x,x+1]

as pointed out by @wim, you can check the memory location with id(point)

+2
source

This line point = [x, x + 1]does 2 things, mainly:

  • [x, x + 1]creates a new list. At this point, python does not know if you are going to use the list pointwhen creating the list or what you are going to do with it.
  • point = ... affects the newly created list on the previous list and releases the previous list.
+2
source

Source: https://habr.com/ru/post/1530087/


All Articles