-1

I have written this code but it is not removing all the elements from the list but only 3 items are removing. Please check what i am doing wrong

names = ["John","Marry","Scala","Micheal","Don"]
if names:
 for name in names:
  print(name)
  print(f"Removing {name} from the list")
  names.remove(name)
print("The list is empty")
khelwood
  • 55,782
  • 14
  • 81
  • 108
Benny khatri
  • 7
  • 1
  • 5

3 Answers3

1

To actually clear a list in-place, you can use any of these ways:

alist.clear()  # Python 3.3+, most obvious
del alist[:]
alist[:] = []
alist *= 0     # fastest

and the problem of your code is that names must be names[:] because when for loop iterating through the list it considerss an index number and while you removing some indexes you change that, so it jumps over some indexes

Omk
  • 1
  • 2
  • 16
  • How do you know the last one is the fastest? Do you have benchmarks? That would be interesting. Also, assigning the empty tuple might be faster than assigning an empty list. – superb rain Aug 09 '20 at 07:12
0
names = ["John","Marry","Scala","Micheal","Don"]
if names:
 for name in names[:]:
  print(name)
  print(f"Removing {name} from the list")
  names.remove(name)
print("The list is empty")

Just assign full names list in your for loop by names[:]

John
Removing John from the list
Marry
Removing Marry from the list
Scala
Removing Scala from the list
Micheal
Removing Micheal from the list
Don
Removing Don from the list
The list is empty
msjahid
  • 66
  • 2
  • Thanks this solution actually worked but i am still somewhat confuse about the use of names[:] instead of just names. If you can elaborate it i will be really helpful for me. – Benny khatri Aug 09 '20 at 07:46
0

Just use names.clear() this will clear whole list

Sekizyo
  • 26
  • 5