First Non-Empty String in list in Python

PythonServer Side ProgrammingProgramming

Given a list of strings, lets find out the first non-empty element. The challenge is – there may be one, two or many number of empty strings in the beginning of the list and we have to dynamically find out the first non-empty string.

With next

We apply the next function to keep moving to the next element if the current element is null.

Example

 Live Demo

listA = ['','top', 'pot', 'hot', ' ','shot']
# Given list
print("Given list:\n " ,listA)
# using next()
res = next(sub for sub in listA if sub)
# printing result
print("The first non empty string is : \n",res)

Output

Running the above code gives us the following result −

Given list:
['', 'top', 'pot', 'hot', ' ', 'shot']
The first non empty string is :
top

With filer

We can also achieve this using the filter condition. The filter condition will discard the null value and we will pick up the first not null value. Only with python2.

Example

 Live Demo

listA = ['','top', 'pot', 'hot', ' ','shot']
# Given list
print("Given list:\n " ,listA)
# using filter()
res = filter(None, listA)[0]
# printing result
print("The first non empty string is : \n",res)

Output

Running the above code gives us the following result −

Given list:
['', 'top', 'pot', 'hot', ' ', 'shot']
The first non empty string is :
top
raja
Published on 04-Jun-2020 12:01:38
Advertisements