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
  • 18,193
  • 10
  • 62
  • 78
LukeG
  • 99
  • 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
  • 228,001
  • 34
  • 392
  • 371
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
  • 12,648
  • 3
  • 32
  • 70