Search code examples
pythonlist

for loop not removing all items from list,what is the solution?


I know why this loop not deleting all the items from list1 with the help of other answers to same question, my question here is what change to made in loop code to remove all the items from list1.

Here is my code:

    list1 = [1,'one',2,'two',3,'three']
    for x in list1:
      if x in list1:
        list1.remove(x)
    print(list1)

Thanks in advance.


Solution

  • You could just do this:

    list1 = []
    

    However if you want to delete each element then:

    while list1!=[]:
        del list1[0]
    

    EDIT: Much better and faster method as suggested by Yann Vernier:

    del list1[:]