0

I know that you can simply:

list = [a, b, c, d, e]

for index in list:
    list.remove(index)

but is there a faster way with a single command like:

list.remove(all)

or something along those lines?

Iain Samuel McLean Elder
  • 19,791
  • 12
  • 64
  • 80
LukeG
  • 109
  • 2
  • 9

3 Answers3

5

You can use del and Explain Python's slice notation:

>>> lst = [1, 2, 3, 4]
>>> del lst[:]
>>> lst
[]
>>>
>>> lst = [1, 2, 3, 4]
>>> id(lst)
34212720
>>> del lst[:]
>>> id(lst)  # Note that the list object remains the same
34212720
>>>
Community
  • 1
  • 1
1

Yes, you can do del myList[:]. (Don't use list as a variable name, it blocks access to the builtin type called list.)

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

One way I can think of:

myList[:] = []

Or another way can be assigning None to the list, the garbage collector will free up the memory eventually.

("list" is not a good name for a list in python, it's already a type)

Sufian Latif
  • 13,086
  • 3
  • 33
  • 70