Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Get Nth word in given String
Next article icon

Python | Extract Nth words in Strings List

Last Updated : 18 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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

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

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

Output
The 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)) 

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:

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.




Next Article
Python - Get Nth word in given String
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Extract odd length words in String
    Sometimes, while working with Python, we can have a problem in which we need to extract certain length words from a string. This can be extraction of odd length words from the string. This can have application in many domains including day-day programming. Lets discuss certain ways in which this tas
    5 min read
  • Python - Get Nth word in given String
    Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which thi
    4 min read
  • Python | Extract words from given string
    In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation
    5 min read
  • Extract words starting with K in String List - Python
    In this article, we will explore various methods to extract words starting with K in String List. The simplest way to do is by using a loop. Using a LoopWe use a loop (for loop) to iterate through each word in the list and check if it starts with the exact character (case-sensitive) provided in the
    2 min read
  • Python - List Words Frequency in String
    Given a List of Words, Map frequency of each to occurrence in String. Input : test_str = 'geeksforgeeks is best for geeks and best for CS', count_list = ['best', 'geeksforgeeks', 'computer'] Output : [2, 1, 0] Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.Input
    4 min read
  • Python - Words Lengths in String
    We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6]. Using Lis
    2 min read
  • Python - Extract K length substrings
    The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in Python Using List Comprehension List comprehension is
    3 min read
  • Extract List of Substrings in List of Strings in Python
    Working with strings is a fundamental aspect of programming, and Python provides a plethora of methods to manipulate and extract substrings efficiently. When dealing with a list of strings, extracting specific substrings can be a common requirement. In this article, we will explore five simple and c
    3 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
  • Create a List of Strings in Python
    Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences