The concept under the hood about "delete" in Python

182 Views Asked by At

I create a varibale temp = [10]

Then I put temp into another list variable ls

After that, I use del temp to delete the temp variable

However, I check ls and still find that [10] is in ls

In my intuition, ls should be printed as [], but things don't go like that.

I want to ask the deep concept of del in Python and maybe some information of copy by reference and copy by value in Python

My code:

temp = [10]
print('id of temp:', id(temp))

ls = [temp]
print('ls before del:', ls)  # ls before del: [[10]]

del temp
print('ls after del:', ls)  # ls after del: [[10]]
print('id of ls[0]:', id(ls[0]))
1

There are 1 best solutions below

1
On

I dont suggest using del on list instead use pop or remove.

Remove

nums = ['1','2']
# remove '2'
nums.remove('2')

output

['1']

pop

nums = ['1','2']
# remove with index of 0
nums.pop(0)

output

['2']

Your Case

firstList = [1]
secondList = [firstList] #[[1]]
print(secondList.pop(0))
#or
print(secondList.remove(firstList))