0
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

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • 1
    after removing one element size of the list also remove so for loop not removing all elimentt – sourab maity Dec 01 '20 at 04:55
  • 2
    **Don't mutate the list while iterating through it**. And rthe result would be `[4, 6]` in Cpython3.8. After you remove 1st element, now `4` is 1st element but iteration index is at 2nd, it removes `5` which at 2nd index, now `6` comes to 2nd index, iteration index become 3 and stops. – Ch3steR Dec 01 '20 at 04:57

3 Answers3

3

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)
theWellHopeErr
  • 1,856
  • 7
  • 22
0

use clear to clear all the element of the list

lis =[3,4,5,6]
lis.clear()
print(lis) 

Output:

[]
sourab maity
  • 1,025
  • 2
  • 8
  • 16
0

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

[]
Shadowcoder
  • 962
  • 1
  • 6
  • 18