I have the list
a = [1,2,0,3,0]
And I need to delete the zeros so that the list to have this
a = [1,2,3]
I have the list
a = [1,2,0,3,0]
And I need to delete the zeros so that the list to have this
a = [1,2,3]
In general, removing things from a data structure while traversing the structure is dangerous. It is the equivalent of sawing a branch of a tree while sitting on it: -)
The typical strategy is to make a function that, instead of eliminating elements, create a new empty list and add elements of the other, skipping the ones you would like to eliminate, to finally return the new list.
Using this idea:
def elimina_ceros(original):
nueva = []
for dato in original:
if dato != 0:
nueva.append(dato)
return nueva
a = [1,2,0,3,0]
a = elimina_ceros(a)
And if you use the syntax list comprehension you can save the previous function and the thing is as simple as:
>>> a = [1,2,0,3,0]
>>> a = [elemento for elemento in a if elemento !=0]
>>> a
[1, 2, 3]
Keep in mind that, both in the case of the function and in the list comprehension , we are not removing anything from the original list, but creating a new one. However, when assigning the result to the same variable a
, the original list will be "unnamed" and the python garbage collector will delete it from memory.
Update The user suggested in a comment to use a.remove(0)
as part of a for
loop in which zeros are detected. This approach does not work well as can be seen in the following example:
a = [1,0,2,0,0,3,4,0]
for i in a:
if i==0:
a.remove(0)
print(a) # Incluyo este print para ver cosas raras
The output is:
[1, 0, 2, 0, 0, 3, 4, 0]
[1, 2, 0, 0, 3, 4, 0]
[1, 2, 0, 3, 4, 0]
[1, 2, 0, 3, 4, 0]
[1, 2, 0, 3, 4, 0]
[1, 2, 3, 4, 0]
And the final value of a
is [1, 2, 3, 4, 0]
where we see that all zeros have not been removed. Look specifically at the outputs in the third, fourth and fifth iterations of the loop. They are equal!
This is precisely what I meant when I said that it is not safe to delete elements while iterating through them. The for
builds an iterator from the initial list, if that list is changed within for
the results are unpredictable.
But that idea has suggested another even uglier one :-) It's about repeatedly calling a.remove(0)
until there are no more zeros left. But in this case without using an iterator, but simply "insisting" in an infinite loop, until we get the exception ValueError
that occurs when we try to eliminate a zero and there is no more.
The (horrible) code is this. I put it only as a curiosity. Do not try it at home:
a = [1,0,2,0,0,3,4,0]
while True:
try:
a.remove(0)
except ValueError:
break
Create another list and use it as an accumulator:
a = [1,2,0,3,0]
b=[]
for i in a:
if i!=0:
b.append(i)
b will result in: [1, 2, 3]
.