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?

3
  • 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. Commented Jun 23, 2019 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. Commented Jun 23, 2019 at 12:43
  • Possible duplicate of Is there a simple way to delete a list element by value? Commented Jun 23, 2019 at 12:52

3 Answers 3

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].

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.