Try a list comprehension.
X = [0,5,0,0,3,1,15,0,12]
X = [i for i in X if i != 0]
Answer from JahKnows on Stack OverflowLets say I have a list:
lyst = [1, 0, 4, 3, 0, 1, 0, 0, 0]
but I want to turn it into:
lyst = [1, 0, 4, 3, 0, 1]
How would I go about doing this? I'm trying to do synthetic division, so I need to cut out trailing zeros while leaving the zeros in between numbers protected.
Videos
Hi all,
let's say i have a list
result = [0, 0, 4, 5, 1, 3]
and i want to remove the leading zeroes from that list.
here is my code, is it pythonic?
for i in range(len(result)):
if result[i] != 0:
result = result[i:]
breakthis is part of the exercise, in the book 'Elements of programming interviews' i found code that is more complicated and i tottaly don't get it (but it works)
result = result[next((i for i, x in enumerate(result) if x != 0),
len(result)):] or [0]can someone explain me this? this is the best way to make it? I have read about next() function and i get that in the end this is result = result[2:].
Does this make sense
def remove_values(the_list, val):
return [value for value in the_list if value != val]
x = [1, 0, 3, 4, 0, 0, 3]
x = remove_values(x, 0)
print x
# [1, 3, 4, 3]
Try using filter method:
list = [9,8,7,6,5,4,3,2,1,0,0,0,0,0,0]
filter(lambda x: x != 0,a) #iterates items, returning the ones that meet the condition in the lambda function
# [9, 8, 7, 6, 5, 4, 3, 2, 1]