0
list1 = [2,5,61,7,10]
list1.remove(list1[0:len(list1)-1])
print(list1)

I want to remove all elements from that list but it shows me syntax error. Any idea how can I remove all elements and print the final result like []

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
The miner
  • 1
  • 1

2 Answers2

2

To remove all list items just use the in-built .clear() function:

>>> list1 = [2,5,61,7,10]
>>> list1.clear()
>>> print(list1)
[]
>>> 
smoggers
  • 3,154
  • 6
  • 26
  • 38
  • Ok but also are there any avalabile options to remove a specified range for example (0:2) ; not just all elements – The miner Aug 26 '18 at 18:06
  • your question did say 'I want to remove **all** elements' but if you also want to remove only a range of elements this can be done using iBug's answer below to use the _slicing_ approach – smoggers Aug 26 '18 at 20:25
0

If you want to remove all elements from a list, you can use the slice assignment:

list1[:] = []

But with list.remove(), you can only do it one-by-one:

for item in list(list1):
    list1.remove(item)

Note I created a copy of list1 with the for loop because it's dangerous to modify what you're iterating over, while it's safe to modify the list while iterating over a copy of it.

To remove some of the items:

for item in list1[0:3]:
    list1.remove(item)

Or just better yet, use slice assignment:

list1[0:3] = []
iBug
  • 35,554
  • 7
  • 89
  • 134