Get first non None value from List in Python

This tutorial will discuss about unique ways to get first non None value from a list in Python.

Table Of Contents

Method 1: Using Generator expression and next() method

To get the first non None value from List, use the generator expression to get an iterator of only non None values from list. Then Pass that iterator to next() function to get the first non None value from the list. If there are only None values in list, then the next() function will return None in this case.

Let’s see the complete example,

listOfValues = [None, None, None, None, 34, 71, None, 45, None]

# Get first non None value from List
value = next((elem for elem in listOfValues if elem is not None), None)

if value:
    print('First none None value is : ', value)
else:
    print('All values are None in list')

Output

First none None value is :  34

Method 2: Using for-loop

To get the first non None value from List, use the following logic:

Create a variable value and initialize it with value None. Then iterate over all elements of list using a for loop. During iteration, for each element check if it is None or not. As soon as a non None element is found, assign that to variable value and break the loop. If there are all None elements in list, then at the end of loop, value field will have None value, otherwise it will have the first non None value.

Let’s see the complete example,

listOfValues = [None, None, None, None, 34, 71, None, 45, None]

value = None

# iterate over all elements of List
for elem in listOfValues:
    # check if element is not None
    if elem != None:
        value = elem
        break

if value:
    print('First none None value is : ', value)
else:
    print('All values are None in list')

Output

First none None value is :  34

Summary

We learned about different ways to get the first non None value from a List in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top