Python | First Non-Empty String in list

Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the 1st valid element. Let’s discuss certain ways in which we can find the first Non-Empty String.

Method #1 : Using next() + list comprehension
The next function returns the iterator and hence its more efficient that conventional list comprehension and the logic part is handled using list comprehension which checks for the last None value.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# First Non-Empty String in list
# using next() + list comprehension
  
# initializing list
test_list = ["", "", "Akshat", "Nikhil"]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using next() + list comprehension
# First Non-Empty String in list
res = next(sub for sub in test_list if sub)
  
# printing result
print("The first non empty string is : " + str(res))

chevron_right


Output :



The original list : ['', '', 'Akshat', 'Nikhil']
The first non empty string is : Akshat

 

Method #2 : Using filter()
The filter function can be used to find the Non empty strings and the 0th index is returned to get the first string among those. Works only with Python 2.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# First Non-Empty String in list
# using filter()
  
# initializing list
test_list = ["", "", "Akshat", "Nikhil"]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using filter()
# First Non-Empty String in list
res = filter(None, test_list)[0]
  
# printing result
print("The first non empty string is : " + str(res))

chevron_right


Output :

The original list : ['', '', 'Akshat', 'Nikhil']
The first non empty string is : Akshat


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.