Python | Extract K sized strings
Last Updated :
13 Apr, 2023
Sometimes, while working with huge amount of data, we can have a problem in which we need to extract just specific sized strings. This kind of problem can occur during validation cases across many domains. Let’s discuss certain ways to handle this in Python strings list.
Method #1 : Using list comprehension + len()
The combination of above functionalities can be used to perform this task. In this, we iterate for all the strings and return only K sized strings checked using len().
Python3
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'geeks' ]
print ("The original list : " + str (test_list))
K = 3
res = [ele for ele in test_list if len (ele) = = K]
print ("The K sized strings are : " + str (res))
|
Output :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The K sized strings are : ['gfg', 'for']
Time Complexity: O(n), where n is the length of the input list. This is because we’re using list comprehension + len() which has a time complexity of O(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 #2 : Using filter() + lambda
The combination of above functionalities can be used to perform this task. In this, we extract the elements using filter() and logic is compiled in a lambda function.
Python3
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'geeks' ]
print ("The original list : " + str (test_list))
K = 3
res = list ( filter ( lambda ele: len (ele) = = K, test_list))
print ("The K sized strings are : " + str (res))
|
Output :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The K sized strings are : ['gfg', 'for']
Time complexity: O(n), where n is the length of the numbers list. The filter() + lambda function has a constant time complexity of O(n)
Auxiliary Space: O(n), as we create new list res where n is the length of the numbers list.
Method #3: Using map() function and lambda expression
Algorithm:
- Initialize the list and K
- Apply filter() and lambda expression to filter out the strings with length equal to K
- Apply map() and lambda expression to get the filtered strings
- Convert the result to a list
- Print the output
Below is the implementation of the above approach:
Python3
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'geeks' ]
print ( "The original list : " + str (test_list))
K = 3
res = list ( map ( lambda x:x, filter ( lambda x: len (x) = = K, test_list)))
print ( "The K sized strings are : " + str (res))
|
Output
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The K sized strings are : ['gfg', 'for']
Time complexity:
The time complexity of filter() function is O(N) where N is the length of the list. The lambda function inside filter() function has a time complexity of O(1). The map() function also has a time complexity of O(N). The lambda function inside map() function has a time complexity of O(1). Therefore, the overall time complexity of the code is O(N).
Auxiliary space:
The space complexity of filter() function and map() function is O(1) as they are not creating any additional space. Therefore, the overall space complexity of the code is also O(N).
Method #4: Using a for loop
- Initialize an empty list res to store the K sized strings.
- Loop through each element ele in the input list test_list.
- Check if the length of ele is equal to K. If yes, append ele to res.
- Once all elements have been checked, return res.
Below is the implementation of the above approach:
Python3
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'geeks' ]
print ( "The original list : " + str (test_list))
K = 3
res = []
for ele in test_list:
if len (ele) = = K:
res.append(ele)
print ( "The K sized strings are : " + str (res))
|
Output
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The K sized strings are : ['gfg', 'for']
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of strings of length K in the input list (worst case is when all strings have length K and thus the new list will have k elements).
Similar Reads
Python - Extract range sized strings
Sometimes, while working with huge amount of data, we can have a problem in which we need to extract just specific range sized strings. This kind of problem can occur during validation cases across many domains. Letâs discuss certain ways to handle this in Python strings list. Method #1 : Using list
4 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
Python Extract Substring Using Regex
Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
2 min read
Size of String in Memory - Python
There can be situations in which we require to get the size that the string takes in bytes using Python which is usually useful in case one is working with files. Let's discuss certain ways in which this can be performed. Using sys.getsizeof()This task can also be performed by one of the system call
2 min read
Similarity Metrics of Strings - Python
In Python, we often need to measure the similarity between two strings. For example, consider the strings "geeks" and "geeky" âwe might want to know how closely they match, whether for tasks like comparing user inputs or finding duplicate entries. Let's explore different methods to compute string si
3 min read
Python | Exceptional Split in String
Sometimes, while working with Strings, we may need to perform the split operation. The straightforward split is easy. But sometimes, we may have a problem in which we need to perform split on certain characters but have exceptions. This discusses split on comma, with the exception that comma should
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
Python - Extract string between two substrings
The problem is to extract the portion of a string that lies between two specified substrings. For example, in the string "Hello [World]!", if the substrings are "[" and "]", the goal is to extract "World". If the starting or ending substring is missing, handle the case appropriately (e.g., return an
3 min read
Python - Extract rows with Even length strings
In this article, we have a given Matrix, and extract rows that are of even lengths. Input : test_list = [["gfg", "is", "best"], ["best", "good", "geek"], ["is", "better"], ["for", "cs"]] Output : [['best', 'good', 'geek'], ['is', 'better']] Explanation : All strings are of even length.Input : test_l
8 min read
Python - Extract words starting with K in String List
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