Python | Kth Non-None String from Rear
Last Updated :
12 Apr, 2023
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 Kth valid element from rear. Let’s discuss certain ways in which we can find the Kth Non-Empty String from rear.
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. The rear part is handled by reversing the list.
Python3
# Python3 code to demonstrate
# Kth Non-None String from Rear
# using next() + list comprehension
# initializing list
test_list = ["", "", "Akshat", "Nikhil"]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 2
# using next() + list comprehension
# Kth Non-None String from Rear
test_list.reverse()
test_list = iter(test_list)
for idx in range(0, K):
res = next(sub for sub in test_list if sub)
# printing result
print("The Kth non empty string from rear is : " + str(res))
Output : The original list : ['', '', 'Akshat', 'Nikhil']
The Kth non empty string from rear is : Akshat
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list res list
Method #2: Using filter() The filter function can be used to find the non-empty strings and the -Kth index is returned to get the last Kth string among those. Works only with Python 2.
Python
# Python code to demonstrate
# Kth Non-None String from Rear
# using filter()
# initializing list
test_list = ["", "", "Akshat", "Nikhil"]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 2
# using filter()
# Kth Non-None String from Rear
res = filter(None, test_list)[-K]
# printing result
print("The Kth non empty string from rear is : " + str(res))
Output : The original list : ['', '', 'Akshat', 'Nikhil']
The Kth non empty string from rear is : Akshat
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), n is the number of elements in the list res list.
Method #3: Using a loop to count non-empty strings from the end
STEPS:
- Initialize a counter variable count to 0 and a string variable result to None.
- Start iterating the list from the end using a reversed loop.
- Check if the current element is non-empty using the bool() function. If it's empty, continue to the next element.
- If the current element is non-empty, increment the count variable by 1.
- Check if the count variable equals K. If it does, assign the current element to result and break the loop.
- After the loop, check if result is still None. If it is, then there were fewer than K non-empty elements in the list, so raise an error.
- If result is not None, then return it as the Kth non-empty string from the rear.
Python3
# Python code to demonstrate
# Kth Non-None String from Rear
# using a loop to count non-empty strings from the end
# initializing list
test_list = ["", "", "Akshat", "Nikhil"]
# printing original list
print("The original list: " + str(test_list))
# initializing K
K = 2
# using a loop to count non-empty strings from the end
count = 0
result = None
for s in reversed(test_list):
if bool(s):
count += 1
if count == K:
result = s
break
# checking if result is None
if result is None:
raise ValueError(
"There are fewer than {} non-empty strings in the list.".format(K))
# printing result
print("The Kth non-empty string from rear is: " + result)
OutputThe original list: ['', '', 'Akshat', 'Nikhil']
The Kth non-empty string from rear is: Akshat
Time complexity: O(n) where n is the length of the list since we need to iterate through the entire list.
Auxiliary space: O(1) since we're only using a constant amount of extra space for variables.
Method 4: Using reversed() and filter()
steps for this approach:
Use the reversed() function to iterate through the list in reverse order.
Use the filter() function to create a new iterator that only contains the non-empty strings.
Use the next() function to iterate through the filtered iterator until you reach the Kth element.
Return the Kth element.
Python3
# Python code to demonstrate
# Kth Non-None String from Rear
# using reversed() and filter()
# initializing list
test_list = ["", "", "Akshat", "Nikhil"]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 2
# using reversed() and filter()
# Kth Non-None String from Rear
filtered_list = filter(None, reversed(test_list))
res = next(filtered_list) # get the last non-empty element
for i in range(K - 1): # iterate until we reach the Kth non-empty element
res = next(filtered_list)
# printing result
print("The Kth non empty string from rear is : " + str(res))
OutputThe original list : ['', '', 'Akshat', 'Nikhil']
The Kth non empty string from rear is : Akshat
The time complexity of this approach is O(N), where N is the length of the list, because we need to iterate through the entire list to find the Kth non-empty element.
The space complexity is O(1), because we only need to store a constant amount of additional data (the Kth non-empty element).
Similar Reads
Python | First character occurrence from rear String There are many ways to find out the first index of element in String as python in its language provides index() function that returns the index of first occurrence of element in String. But if one desires to get the last occurrence of element in string, usually a longer method has to be applied. Let
4 min read
Python | Remove Kth character from strings list Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor
7 min read
Python - Phrase removal in String Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
2 min read
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 ca
5 min read
Python - Convert None to empty string In Python, it's common to encounter None values in variables or expressions. In this article, we will explore various methods to convert None into an empty string.Using Ternary Conditional OperatorThe ternary conditional operator in Python provides a concise way to perform conditional operations wit
2 min read