0

I am trying to clear a python list by removing every element in loop by code

x=list(range(10000))
for i in x:
    x.remove(i)

I thought that after this code x must be [], but instead only every second element of list is removed. len(x)=5000 instead of 0.

Why is it so? What am I doing wrong. Thanks

skeeph
  • 462
  • 2
  • 6
  • 18

4 Answers4

2

The a.remove(i) messed up the indexing is my guess.

instead use

a.clear()

Its a good way to clear a list.

Sidhin S Thomas
  • 875
  • 1
  • 8
  • 19
1

If you want to clear a python list like you're doing, the right way is just using x.clear, docs about that method here, now, if you want to remove elements using some fancy conditions, just use filter, example clearing the whole x list:

x = list(range(10000))
x = filter(lambda x: False, x)
print x
BPL
  • 9,632
  • 9
  • 59
  • 117
0

If you want to implement a list object that erases itself while iterating over it that would be fairly easy:

class ErasingList(list):
    "a list implemented as an iterator, iterating over it will .pop() items off"
    def __iter__(self):
        return self
    def __next__(self):
        try:
            return self.pop(0)
        #or self.pop() to take from the end of the list which is less intuitive but more efficient
        except IndexError:
            raise StopIteration
    next = __next__ #vs2 compatibility.

x = ErasingList(range(100))

for i in x:
    print(i)

print(x)
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
0
original_list = list(range(1000))
remove_list_elements = []

for i in range(0, len(original_list), 2): 
    remove_list_elements.append(original_list[i])

[original_list.remove(i) for i in remove_list_elements] 
print(len(original_list))
Attila
  • 51
  • 3