Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Inline if to print non-empty strings?

I'm trying to print out just the non-empty strings in a list. I can't seem to get the below to work, what am I doing wrong??

print item in mylist if item is not ""
like image 456
Sid Avatar asked Jun 21 '26 10:06

Sid


1 Answers

The following is invalid syntax: print item in mylist if item is not ""

You could perhaps achieve what you want using a list comprehension:

>>> mylist = ["foo","bar","","baz"]
>>> print [item for item in mylist if item]
['foo', 'bar', 'baz']
like image 182
MattH Avatar answered Jun 22 '26 23:06

MattH