Reputation: 21
I genuinely do not understand why this code
a = [1,2,3,4,5,6,7,8,9]
while a[0]:
a.remove(a[0])
print(a)
does not work. The message I receive is "list index out of range". But is Python not checking if there even was a item in the list in the first place? Thanks
Upvotes: 2
Views: 87
Reputation: 273
What happens when you run that code is that you're telling python to keep looping while a[0] (the first element of the list a) exists. Each time the loop runs you remove the current first element from the list. When there are no more elements to remove python throws exception at your while a[0] condition. To avoid this you can do the following:
a = [1,2,3,4,5,6,7,8,9]
try:
while a[0]:
print "removing the element:", a[0]
a.remove(a[0])
except IndexError:
print "no more elements to remove."
This will smoothly handle the error message.
or you could have:
while len(a) > 0:
which will only run as long as your list contains at least one element.
Note that trying to print what you're doing can often help you debug your code.
You can read this discussion:
Upvotes: 1
Reputation: 3244
When while checks for last a[0]
, the 0 index itself is out of range. May be you want to use len(a)
a = [1,2,3,4,5,6,7,8,9]
while len(a):
a.remove(a[0])
print(a)
Though its not going to print anything other than []
Upvotes: 1
Reputation: 95948
Think what will happen when your list is empty:
a = []
Then you have:
while a[0]:
but.. the list is empty, you'll get out of bounds, example:
a = [1,2,3]
while a[0]:
a.remove(a[0])
# first iteration: a = [2, 3]
# second iteration: a = [3]
# third iteration: a = []
# fourth iteration: out of bounds since there's no a[0]
Solution:
Change while a[0]
to while a
.
Upvotes: 4