I have a list of strings, some which happen to be None:
headers = ['Name', None, 'HW1', 'HW2', None, 'HW4', 'EX1', None, None]
Now I would like to iterate over this list, but skip the None entries. For instance, something like this would be nice:
for header in headers if header: print(header)
But this doesn't work. There are two ways I could get this to work, but I don't like either method:
for header in (item for item in headers if item): print(header)
and
for header in headers:
if header: print(header)
I just was curious if there was a better way. I feel like ignoring None's should be quite fundamental.
Use the all() function to check if all items in a list are None in Python, e.g. if all(i is None for i in my_list): . The all() function takes an iterable as an argument and returns True if all of the elements in the iterable are truthy (or the iterable is empty).
The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.
a) keep the code clean and simple (not storing the result in a var and do if != None, etc..) b) treat a None return value like an empty list i.e. do not run the loop and silently ignore the fact that function returned a None value.
headers = ['Name', None, 'HW1', 'HW2', None, 'HW4', 'EX1', None, None]
for header in filter(None, headers):
print header
You can use filter
:
headers = filter(None, headers)
You can get rid of the None
items with a list comprehension:
headers = [item for item in headers if item is not None]
for item in header:
print item
You can filter out the Nones
with a simple list comprehension:
headers = [header for header in headers if header]
Then call your code:
for header in headers:
print(header)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With