0

So, I have a list of random elements lst1 = [1,"random",67,9,32,7.6,5/2] when I loop over it to remove all it's elements ,I Get this Output ['random', 9, 7.6]

this is what i did :

for i in lst1 :
    lst1.remove(i)
print(lst1) 

In Second case When I do the same with this syntax

for i in lst1[:]:
   lst1.remove(i)

It removes all elements -> []

Can someone tell me what's really happening in both the cases And why it doesn't remove all elements in first case

mohitattr
  • 23
  • 4
  • Apart from this being a duplicate, if you want to remove all elements from the list, which not simply use `lst1 = []`. Unless you have multiple references to the list (in which case, are you sure you can just remove all contents?), this removes the `lst1` assignment and if that was the last reference to it, the old list and its contents will be garbage-collected. – Grismar Feb 04 '22 at 04:41

1 Answers1

-1

Remove method removes only a first occurrence of the given argument

Try this code

lst1.clear()

this doesn't require the loop

Harish3124
  • 114
  • 1
  • 6