Different sequences disappear in python sequences

Asked 2 years ago, Updated 2 years ago, 70 views

 values=["0", "1", "2", "3", "4" ]
num = ["a", "b", "c", "d", "e" ]
num_tmp = [ ]

num_tmp = num

for value in values:
    num = num_tmp
    print(num)
    print(num_tmp)
    num.clear()

In the above case, the value is num=["a", "b", "c", "d", "e"], but if the value is 2,3,4, both num and num_tmp will be [] clear only.

python array

2022-09-30 21:38

2 Answers

Python actually remembers references to a list object as variables (names) when you substitute a list for a variable.Internally, the image contains the memory address in the variable.If you substitute num_tmp=num for the list num, the two variables point to the same list object, and in fact id(num) and id(num_tmp) match.Editing the contents of the list does not change the id.

>>num=[1,2,3]
>>num_tmp=num
>>>id(num)
2749981156232
>>>id(num_tmp)
2749981156232
>>num[1] = 42
>>num
[1, 42, 3]
>>num_tmp
[1, 42, 3]
>>>id(num)
2749981156232

Therefore, if you copy it as a different object, the two variables point to another list object.You can do this by using copy.copy() or copy.deepcopy().

Alternatively, a one-dimensional list can be copied as follows:This is substituted from a slice that shows the full range of the list num.

By the way, if I do num.clear() every time at the end of the loop like this sample program, do I need to use num_tmp in the first place? It looks like I just need to use num.It's probably not your actual program, so it's hard to judge, but please consider whether you really need temporary variables.


2022-09-30 21:38

It is true that num=num_tmp produces the same memory id.

 values=["0", "1", "2", "3", "4" ]
num = ["a", "b", "c", "d", "e" ]
num_tmp = [ ]
num_tmp = num
for value in values:
    num = num_tmp
    print(num)
    print(id(num))
    print(num_tmp)
    print(id(num_tmp))
    num=[]←I was able to change this to [].

when done.

['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408 ['a', 'b', 'c', 'd', 'e']
2657197582408

Now, the mysterious num=num_temp has been replaced.

The addresses are the same.


2022-09-30 21:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.