Say I have an array:
array=[1,0,2,3,4,0,0,5,6,0]
I want a list that returns just the numbers and not zeros. So I did this and it works:
print(list(y for y in array if y!=0)
I tried another way without list comprehension and it won't work, can someone explain why?
for y in array:
if y!=0:
print(list(y))
What would be another way to print a list of just the numbers without the 0's?
Edit: I tried to solve this problem using a for loop, and it works if I make an empty list on top. It works, but I don't understand why! But why does this work and other one doesn't? What's more efficient, this or the list comprehension in terms of speed/memory?
array=[1,0,2,3,4,0,0,5,6,0]
list=[]
for y in array:
if y!=0:
list.append(y)
print(list)