Python | Extract Nth words in Strings List
Last Updated :
18 Mar, 2024
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 geeks', '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))
OutputThe original list is : ['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'geeks', '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 geeks', '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))
OutputThe original list is : ['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'geeks', '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 geeks', '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))
OutputThe original list is :['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'geeks', '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 geeks', '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))
OutputThe Nth words in list are : ['best', 'geeks', '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 geeks', '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 geeks', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'geeks', '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.
Method#6:
Using the re.findall() function to extract words from each string in the list and then selects the Nth word from each list if it exists. The result is a list containing the Nth words from each string.
Step-by-Step Approach
- Import the re module.
- Create a list named test_list containing strings.
- Print the original list to the console.
- Set the value of N to 2.
- Use a list comprehension to iterate over each string in test_list.
- For each string, extract all words using re.findall(r’\b\w+\b’, sub).
- Select the Nth word ([N-1]) if it exists (if len(…) > N-1).
- Store the results in the res list.
- Print the list of Nth words obtained in the previous step.
Python3
import re
# initializing list
test_list = ['Gfg best for', 'All geeks', '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 re.findall()
res = [re.findall(r'\b\w+\b', sub)[N-1] for sub in test_list if len(re.findall(r'\b\w+\b', sub)) > N-1]
# printing result
print("The Nth words in list are : " + str(res))
OutputThe original list is :['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'geeks', 'is', 'CS']
Time Complexity:
The time complexity is O(N * M), where N is the number of strings in test_list and M is the average number of words in each string. This is because, in the worst case, we iterate over each character of each word in each string.
Auxiliary Space Complexity:
The auxiliary space complexity is O(K), where K is the total number of words across all strings in test_list. This is because we store the Nth words in the res list. The space required is proportional to the number of words we extract and store in the result list.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read