Reputation: 139
I am looking for a basic way to exclude printing an item from a list (not remove/delete) if that named value = something specified, e.g. = 0
I thought it would be something basic like this, but I get an error that I is not defined.
a = 2
b = 0
c = 4
d = 0
e = 6
lis = [a,b,c,d,e]
while i != 0 in range(lis):
print (lis[i])
Wanted result:
2
4
6
Seems like I am missing something simple? Or is this not as simple as I imagined?
Upvotes: 0
Views: 4043
Reputation: 17392
Here are the options which you can use.
1) You can use either a normal loop
for i in lis:
if i != 0:
print i
OR
2) List Comprehensions
[i for i in lis if i!=0]
I would still say when coming to Stackoverflow, please consider going through the tutorials, because its the most basic thing in python.
Upvotes: 0
Reputation: 5646
for l in lis:
if l != 0:
print l
Iterate through the items in the list one by one. Every time, check the current item l
to see if it equals 0. Print the item if it is non-zero.
Upvotes: 0
Reputation: 47820
Python syntax doesn't support a conditional where you're trying to apply it. There are several alternatives, though:
You could put the condition inside the loop:
for item in lis:
if item != 0:
print item
You could filter the list:
for item in filter(lambda i: i!=0, lis): # filter(None, lis) works too
print item
Or using a list comprehension (technically a generator expression here):
for item in (i for i in lis if i != 0):
print item
Or skip the loop entirely:
print '\n'.join(str(i) for i in lis if i != 0)
Upvotes: 4