1

I am trying to delete a list within a list but my code is unable to do so even though I have deleted the list.

y = [45]  
x = [1,2,3,5,y]    

del y        
print(x)

Output of printing x:

[1, 2, 3, 5, [45]]

My output shows as [1, 2, 3, 5, [45]] which means list y still exists in list x.
But I deleted list y in my code. Why is list y still not deleted then? Is there something wrong with my code? How do I delete an entire list in Python?

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
Maqruis1
  • 157
  • 1
  • 1
  • 13
  • 2
    `del` deletes references, not objects. In your case you have to use the `.remove()` method of the list `x` and remove all other references to the list, then the list will eventually be garbage collected. – Klaus D. Jun 23 '19 at 12:29
  • When `y` is put into `x`, the value of `y` is retrieved, not a weak reference. This means that though they are the same list, deleting `y` will not remove it from all the places it's used in. If you want, check out the `weakref` module. If you wanted to clear the list, use `list.clear`. – GeeTransit Jun 23 '19 at 12:43
  • Possible duplicate of [Is there a simple way to delete a list element by value?](https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value) – Rakibul Islam Jun 23 '19 at 12:52

3 Answers3

1

Look here and have a play with it.

In python, all variables are just names, which are bound to objects. It is not same as C or C++, where variables are memory locations.

In your code, y and x[4] are both bound to [45], which is a list object. When you del y, you can not stop x[4] from being bound to [45].

LiuXiMin
  • 1,225
  • 8
  • 17
0

If you want to remove n-th element of list, you should use del following way:

y = [45]
x = [1,2,3,5,y]
del x[4] # 4 means last element of x as indexing starts with 0
print(x) # [1,2,3,5]
print(y) # [45]

Note that after that y remains unaltered. lists have also method .remove which will remove first occurence, consider following example:

a = [1,2,3,1,2,3,1,2,3]
a.remove(3)
print(a) # [1, 2, 1, 2, 3, 1, 2, 3]

remove will cause ValueError if there is not element in list.

Daweo
  • 31,313
  • 3
  • 12
  • 25
0

Delete a list which is present inside the another list.

By using remove function,we can also delete a list which is present Inside the other.

Run the Following code:

y = [45]  
x = [1,2,3,5,y]    

x.remove(y)
print(x)

x.remove(y) which removes the y list in the x list.

output:

[1, 2, 3, 5]

Integraty_dev
  • 500
  • 3
  • 18