Skip to content
Related Articles

Related Articles

Improve Article

Python – Filter above Threshold size Strings

  • Last Updated : 31 Dec, 2019

Sometimes, while working with huge amount of data, we can have a problem in which we need to extract just specific sized strings above a minimum threshold. 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 above threshold strings checked using len().




# Python3 code to demonstrate working of
# Filter above Threshold size Strings
# using list comprehension + len()
  
# initialize list 
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize Threshold
thres = 4
  
# Filter above Threshold size Strings
# using list comprehension + len()
res = [ele for ele in test_list if len(ele) >= thres]
  
# printing result
print("The above Threshold size strings are : " + str(res))
Output :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The above Threshold size strings are : ['best', 'geeks']

 

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 code to demonstrate working of
# Filter above Threshold size Strings
# using filter() + lambda
  
# initialize list 
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize Threshold
thres = 4
  
# Filter above Threshold size Strings
# using filter() + lambda
res = list(filter(lambda ele: len(ele) >= thres, test_list))
  
# printing result
print("The above Threshold size strings are : " + str(res))
Output :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The above Threshold size strings are : ['best', 'geeks']

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :