Open In App

Python – Extract words starting with K in String List

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given list of phrases, extract all the Strings with begin with character K.

Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = l 
Output : [‘learning’, ‘love’] 
Explanation : All elements with L as starting letter are extracted. 

Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = m 
Output : [] 
Explanation : No words started from “m” hence no word extracted.

Method #1 : Using loop + split()

This is brute way in which this problem can be solved. In this, we convert each phrase into list of words and then for each word, check if it’s initial character is K. 

Python3




# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
 
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "g"
 
res = []
for sub in test_list:
    # splitting phrases
    temp = sub.split()
    for ele in temp:
 
        # checking for matching elements
        if ele[0].lower() == K.lower():
            res.append(ele)
 
# printing result
print("The filtered elements : " + str(res))


Output

The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']

Time Complexity: O(n*n), where n is the size of list
Auxiliary Space: O(n), where n is the size of list

Method #2 : Using list comprehension + split() 

This is yet another way in which this task can be performed. In this we run double nested loops inside single list comprehension and perform required conditional checks.

Python3




# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using list comprehension + split()
 
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "g"
res = [ele for temp in test_list for ele in temp.split() if ele[0].lower()
       == K.lower()]
 
# printing result
print("The filtered elements : " + str(res))


Output

The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method #3 : Using split(),extend(),lower() and find() methods

Python3




# Python3 code to demonstrate working of
# Extract words starting with K in String List
 
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "g"
 
res = []
x = []
for i in test_list:
    x.extend(i.split())
for j in x:
    if j.lower().find(K) == 0:
        res.append(j)
 
# printing result
print("The filtered elements : " + str(res))


Output

The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']

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 “test_list”.

Method #4 : Using startswith(),upper() and lower() methods

Python3




# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
 
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "g"
 
res = []
x = []
for i in test_list:
    x.extend(i.split())
for i in x:
    if(i.startswith(K) or i.startswith(K.lower()) or i.startswith(K.upper())):
        res.append(i)
 
# printing result
print("The filtered elements : " + str(res))


Output

The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']

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

Method #4 : Using lambda functions, extend(), lower() methods

Python3




# Python3 code to demonstrate working of
# Extract words starting with K in String List
 
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "g"
 
res = []
for i in test_list:
    words = i.split()
    startWords = list(filter(lambda x: x[0].lower() == K.lower(), words))
    res.extend(startWords)
 
# printing result
print("The filtered elements : " + str(res))


Output

The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']

Time Complexity: O(N*M)

Auxiliary Space: O(N*M)

Method #5 : Using itertools.filterfalse() functions

Python3




# Python3 code to demonstrate working of
# Extract words starting with K in String List
import itertools
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "g"
 
res = []
for i in test_list:
    words = i.split()
    startWords = list(itertools.filterfalse(lambda x: x[0].lower() != K.lower(), words))
    res.extend(startWords)
 
# printing result
print("The filtered elements : " + str(res))


Output

The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']

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

Method #6:Using reduce()

  1. Import the reduce() function from the functools module.
  2. Initialize the list of strings test_list and the character K.
  3. Use reduce() with a lambda function that takes two arguments x and y.
  4. Split each string y in the list into words and filter the words that start with the character K.
  5. Append the filtered words to the accumulator list x.
  6. Initialize the initial value of the accumulator as an empty list [].
  7. The final result list will be the value returned by the reduce() function.
  8. Print the final result list.

Python3




# importing reduce module
from functools import reduce
 
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "g"
 
# Extract words starting with K in String List
# Using reduce() + split()
res = reduce(lambda x, y: x + [ele for ele in y.split() if ele[0].lower() == K.lower()], test_list, [])
 
# printing result
print("The filtered elements : " + str(res))
 
#This code is contributed by Vinay Pinjala.


Output

The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']

Time Complexity: O(n*m)

where n is the number of strings in test_list and m is the maximum number of words in any string.
The time complexity of split() is O(m) and the time complexity of filtering words starting with K is also O(m).
Since this process is done for each string in test_list, the overall time complexity is O(n*m).

Space Complexity: O(n*m)

The space complexity is dominated by the list filtered_words which stores the filtered words.
The maximum size of this list can be n*m, if all the words in test_list start with the character K.
The space complexity of reduce() is O(m) because it only stores the intermediate result (the list of filtered words) during each iteration.
Therefore, the overall space complexity is O(n*m).



Similar Reads

Python Program that Extract words starting with Vowel From A list
Given a list with string elements, the following program extracts those elements which start with vowels(a, e, i, o, u). Input : test_list = ["all", "love", "get", "educated", "by", "gfg"] Output : ['all', 'educated'] Explanation : a, e are vowels, hence words extracted.Input : test_list = ["all", "love", "get", "educated", "by", "agfg"] Output : [
5 min read
Python - Eliminate Capital Letter Starting words from String
Sometimes, while working with Python Strings, we can have a problem in which we need to remove all the words beginning with capital letters. Words that begin with capital letters are proper nouns and their occurrence mean different meaning to the sentence and can be sometimes undesired. Let's discuss certain ways in which this task can be performed
7 min read
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 meth
7 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 marks have to be ignored. Input: GeeksForGeeks is
5 min read
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 task can be performed. Method #1 : Using loop This is
5 min read
Regex in Python to put spaces between words starting with capital letters
Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to lowercase Examples: Input : BruceWayneIsBatmanOut
2 min read
Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Extract all capital words from Dataframe in Pandas
In this article, we are to discuss various methods to extract capital words from a dataframe in the pandas module. Below is the dataframe which is going to be used to depict various approaches: C/C++ Code # Import pandas library import pandas # Create dataset data = [['tom', 'DATAFRAME', '200.00'], ['PANDAS', 15, 3.14], ['r2j', 14, 'PYTHON']] # Cre
3 min read
Python - Extract Dictionary values list to List
Sometimes, while working with dictionary records, we can have problems in which we need to extract all the dictionary values into a single separate list. This can have possible application in data domains and web-development. Lets discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression The combinatio
5 min read
three90RightbarBannerImg