Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over non None items in Python

Tags:

python

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.

like image 806
breeden Avatar asked May 20 '15 05:05

breeden


People also ask

How do you check if all items in a list are none Python?

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).

How do you filter none in Python?

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.

How do you iterate through none in Python?

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.


4 Answers

headers = ['Name', None, 'HW1', 'HW2', None, 'HW4', 'EX1', None, None]
for header in filter(None, headers):
    print header
like image 180
Łukasz Rogalski Avatar answered Oct 11 '22 18:10

Łukasz Rogalski


You can use filter:

headers = filter(None, headers)
like image 38
Raniz Avatar answered Oct 11 '22 19:10

Raniz


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
like image 27
David542 Avatar answered Oct 11 '22 19:10

David542


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)
like image 25
user1823 Avatar answered Oct 11 '22 19:10

user1823