Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Extract Nth words in Strings List

Python | Extract Nth words in Strings List

Sometimes, while working with Python Lists, we can have problems in which we need to perform the task of extracting Nth word of each string in List. This can have applications in the web-development domain. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using list comprehension + split() The combination of the above methods can be used to solve this problem. In this, we perform the task of getting Nth word using split and recreate list using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Extract Nth words in Strings List
# Using list comprehension + split()
     
# initializing list
test_list = ['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
 
# printing original list
print("The original list is :" + str(test_list))
 
# initializing N
N = 2
 
# Extract Nth words in Strings List
# Using list comprehension + split()
res = [sub.split()[N - 1] for sub in test_list if len(sub.split()) > 1]
 
# printing result
print("The Nth words in list are : " + str(res))


Output : 

The original list is : ['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'Lazyroar', 'is', 'CS']

Time Complexity: O(n*n) where n is the total number of values in the list “test_list”. 
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.

Method #2: Using list comprehension + enumerate() + split() The combination of above functions can be used to perform this task. In this, we use enumerate to check for the Nth word rather than split(). 

Python3




# Python3 code to demonstrate working of
# Extract Nth words in Strings List
# Using list comprehension + <code>enumerate() + split()
     
# initializing list
test_list = ['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing N
N = 2
 
# Extract Nth words in Strings List
# Using list comprehension + <code>enumerate() + split()
res = [ele for sub in test_list for idx, ele in enumerate(sub.split()) if idx == (N - 1)]
 
# printing result
print("The Nth words in list are : " + str(res))


Output : 

The original list is : ['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'Lazyroar', 'is', 'CS']

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the list comprehension + enumerate() + split() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method #3: Using for loop + append() + split() + indexing

Python3




# Python3 code to demonstrate working of
# Extract Nth words in Strings List
# Using append() and for loop
 
# initializing list
test_list = ['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
 
# printing original list
print("The original list is :" + str(test_list))
 
# initializing N
N = 2
res = []
for i in test_list:
    words = i.split()
    # Extract Nth words in Strings List
    res.append(words[N-1])
 
 
# printing result
print("The Nth words in list are : " + str(res))


Output

The original list is :['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'Lazyroar', 'is', 'CS']

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

Method #4: Using map() and lambda function

This method uses map() function along with a lambda function to apply the split() function on each string in the list and then extract the Nth word using indexing. The resulting list is converted to a list using list() function.

Python3




test_list = ['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
 
N = 2
res = list(map(lambda x: x.split()[N-1], test_list))
 
print("The Nth words in list are : " + str(res))


Output

The Nth words in list are : ['best', 'Lazyroar', 'is', 'CS']

Time complexity: O(n), linear time complexity, where n is the length of the list.
Auxiliary space: O(n), the space required to store the result list is proportional to the length of the list.

Method #5: Using reduce() 

In this method, we reduce() with a lambda function to accumulate the Nth word from each string in the input list. If the string has less than N words, it is skipped. The accumulator acc is initialized to an empty list. The final result is a list of all Nth words in the input list.

Python3




# Python3 code to demonstrate working of
# Extract Nth words in Strings List
# Using reduce() + split()
 
# importing reduce() function from functools module
from functools import reduce
 
# initializing list
test_list = ['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
 
# printing original list
print("The original list is :" + str(test_list))
 
# initializing N
N = 2
 
# Extract Nth words in Strings List
# Using reduce() + split()
res = reduce(lambda acc, sub: acc + [sub.split()[N-1]] if len(sub.split()) > N-1 else acc, test_list, [])
 
# printing result
print("The Nth words in list are : " + str(res))


Output:

The original list is :['Gfg best for', 'All Lazyroar', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'Lazyroar', 'is', 'CS']

Time complexity: O(n), where n is the length of the input list. This is because we need to iterate through every string in the list and perform a split operation on it.
Auxiliary space: O(n), where n is the length of the input list. This is because we create a new list to store the Nth word extracted from each string that satisfies the condition.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments