Skip to content
Related Articles

Related Articles

Python – Length of shortest string in string list

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 17 Dec, 2019

Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum length string of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using min() + generator expression
The combination of above functionalities can be used to perform this task. In this, we extract all the list lengths using generator expression and return minimum of them using min().




# Python3 code to demonstrate working of
# Minimum String length
# using min() + generator expression
  
# initialize list 
test_list = ['gfg', 'is', 'best']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Minimum String length
# using min() + generator expression
res = min(len(ele) for ele in test_list)
  
# printing result
print("Length of minimum string is : " + str(res))

Output :

The original list : ['gfg', 'is', 'best']
Length of minimum string is : 2

 

Method #2 : Using len() + key argument + min()
The combination of above functions can be used to perform this task. In this, we extract the minimum length using len() and min(). It is faster than above method as it performs more task built in rather than overhead by generator expression.




# Python3 code to demonstrate working of
# Minimum String length
# using len() + key argument + min()
  
# initialize list 
test_list = ['gfg', 'is', 'best']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Minimum String length
# using len() + key argument + min()
res = len(min(test_list, key = len))
  
# printing result
print("Length of minimum string is : " + str(res))

Output :

The original list : ['gfg', 'is', 'best']
Length of minimum string is : 2


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!