I have a list that I'm trying to iterate through while removing zeros(0) if any from the list.
The following is the code:
list = [1, 2, 0, 4, 5]
for i in range(len(list)):
if i == 0:
list.remove(i)
print(list[i])
Yes, the code works but raises the error IndexError: list index out of range
as bellow:
1 2 4 5 Traceback (most recent call last): File "M:/Python Workspace/PycharmProjects/untitled/scrapyard.py", line 6, in print(l[i]) IndexError: list index out of range
How do I do away with this error? Thanks.
CodePudding user response:
You can use list comprehension to build a new list from your list excluding zeros:
lst = [1, 2, 0, 4, 5]
a = [x for x in lst if x !=0]
print(a)
Output:
[1, 2, 4, 5]
You can iterate directly through a.
CodePudding user response:
With your code you go to remove an element and consequently the length of the list is changed. In order to remove any zero from the function you can run the following code:
A way is this:
l = [1, 2, 0, 4, 5]
for i in range(0,l.count(0)):
l.remove(0)
Unlike the other ways that others have proposed to you where you go to create copies of the list, with the code I wrote you you go to work on the same list without creating a new list.
CodePudding user response:
The reason is you are iterating using index
and also removing the elements thereby dynamically changing the length of the list
. One of the approaches can be iterate through each element and remove it if it is 0
:
list1 = [1, 2, 0, 4, 5]
for elem in list1:
if elem == 0:
list1.remove(elem)
print (list1)
Also note, it's a bad practice to use list
as variable name as list
is a built-in data structure name in python