Open In App

Python | First Non-Empty String in list

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Python3




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


Output : 

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

Time Complexity: O(n) , where n is the number of elements in the list.
Auxiliary Space: O(m), where m is the length of the first non-empty string.

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. 

Python




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


Output : 

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

Time Complexity: O(n) , where n is the number of elements in the list.
Auxiliary Space: O(m), where m is the length of the first non-empty string.

Method #3: Using len() method.If the length of string is zero then string is empty otherwise it is not empty.

Python3




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


Output

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

Time Complexity: O(n) , where n is the number of elements in the list.
Auxiliary Space: O(m), where m is the length of the first non-empty string.

Method #4:  Using the reduce function: You can use the reduce function from the functools module to find the first non-empty string in the list. The reduce function applies a given function to the elements of the list, starting from the left, and returns a single value.

Python3




# Import the reduce function from the functools module
from functools import reduce
 
# Initialize the list
test_list = ["", "", "Akshat", "Nikhil"]
 
# Find the first non-empty string using the reduce function
res = reduce(lambda s1, s2: s1 or s2, test_list)
 
# Print the result
print("The first non-empty string:", res)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The first non-empty string: Akshat

 Time complexity: O(n), where n is the length of the list.
 Auxiliary Space: O(1)

Method #5 : Using isspace() method

Python3




# Python3 code to demonstrate
# First Non-Empty String in list
 
# initializing list
test_list = ["", "", "Akshat", "Nikhil"]
 
# printing original list
print("The original list : " + str(test_list))
 
 
# First Non-Empty String in list
res=""
for i in test_list:
    x=i+" "
    if(not x.isspace()):
        res=i
        break
# printing result
print("The first non empty string is : " + str(res))


Output

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

Time Complexity : O(N)
Auxiliary Space : O(N)

Method #6: Using numpy:

 Algorithm:

  1. Initialize the list test_list.
  2. Convert the list to a NumPy array arr.
  3. Use the nonzero() function on the array arr to get the indices of the non-zero elements.
  4. Get the first element from the indices using [0][0] because the nonzero() function returns a tuple of arrays,
  5. one for each dimension of the input array, and we are working with a 1-dimensional array.
  6. Get the first non-empty string from the arr array using the index obtained in step 4.
  7. Print the result.

Python3




import numpy as np
 
# Initialize the list
test_list = ["", "", "Akshat", "Nikhil"]
# printing original list
print("The original list : " + str(test_list))
# Convert the list to a NumPy array
arr = np.array(test_list)
 
# Find the index of the first non-empty string using nonzero()
idx = np.nonzero(arr)[0][0]
 
# Get the first non-empty string using the index
res = arr[idx]
 
# Print the result
print("The first non-empty string:", res)
#This code is contributed by vinay Pinjala


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

Time complexity:  O(n), where n is the length of the input list test_list. The nonzero() function in NumPy takes linear time to find the indices of the non-zero elements.
Space complexity:  O(n), where n is the length of the input list test_list. The NumPy array arr created in this code will have the same size as the input list, and hence the space complexity is O(n).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads