lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(lis)
Output:
[3,4]
I tried pop()
also but couldn't remove all elements
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(lis)
Output:
[3,4]
I tried pop()
also but couldn't remove all elements
The reason why you are not able to remove all the elements is that when you are removing an element from the array the j
value skips to the next value's next value instead of the next. So only the alternative values will be removed by this method.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(j)
print(lis)
Output
3
5
[4,6]
As you can see in this output print(j)
does not print all the elements, it only prints 3
and 5
. So only 3
and 5
are removed.
How to solve it?
So you can either use clear()
, like this
lis.clear()
Or if you want to use iteration you can do it with pop()
like this
for i in range(len(lis)):
lis.pop(i)
Or you can create a shallow copy of the list and remove()
the elements one by one like this
for i in list(lis):
lis.remove(i)
Or you can use :
to return the whole slice of the array (copy of the array)
for i in x[:]:
x.remove(i)
use clear to clear all the element of the list
lis =[3,4,5,6]
lis.clear()
print(lis)
Output:
[]
A correct solution will be to create a shallow copy with the help of list()
function.
lis =[3,4,5,6]
for j in list(lis):
lis.remove(j)
print(lis)
Output
[]