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 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 ranged sized strings checked using len().
Python3
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'geeks' ]
print ("The original list : " + str (test_list))
i, j = 2 , 3
res = [ele for ele in test_list if len (ele) > = i and len (ele) < = j]
print ("The range sized strings are : " + str (res))
|
Output :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The range sized strings are : ['gfg', 'is', 'for']
Time Complexity: O(n) where n is the number of elements in the string list. The list comprehension + len() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res 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))
i, j = 2 , 3
res = list ( filter ( lambda ele: len (ele) > = i and len (ele) < = j, test_list))
print ("The range sized strings are : " + str (res))
|
Output :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The range sized strings are : ['gfg', 'is', 'for']
Time Complexity: O(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 #3: Using a for loop and if statement
- Initialize an empty list to store the range-sized strings.
- Iterate over each string in the input list using a for loop.
- Check if the length of the current string is greater than or equal to i and less than or equal to j using an if statement.
- If the condition is true, append the current string to the result list.
- Return the result list.
Python3
test_list = [ 'gfg' , 'is' , 'best' , 'for' , 'geeks' ]
print ( "The original list : " + str (test_list))
i, j = 2 , 3
res = []
for ele in test_list:
if len (ele) > = i and len (ele) < = j:
res.append(ele)
print ( "The range sized strings are : " + str (res))
|
Output
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The range sized strings are : ['gfg', 'is', 'for']
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(m), where m is the number of range sized strings found in the input list.
Last Updated :
13 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...