Python - Smallest Length String
To identify the smallest string by length in a list, we compare the lengths of all strings and select the shortest one.
Using min()
The most efficient way to do this is by using the min() function with the key parameter. This method directly calculates the smallest string based on its length, avoiding the need for explicit looping.
li= ['gfg', 'is', 'best', 'for', 'geeks']
# Finding the smallest string by length
res = min(li, key=len)
print(res)
Output
is
Using sorted()
sorted() function sorts the entire list based on string lengths and the smallest string is the first element.
li = ['gfg', 'is', 'best', 'for', 'geeks']
res = sorted(li, key=len)[0]
print(res)
Output
is
Explanation:
- For the list
li, the lengths are:'gfg'(3),'is'(2),'best'(4),'for'(3), and'geeks'(5). - Sorting the list by length using
sorted(li, key=len)results in['is', 'gfg', 'for', 'best', 'geeks']. - The first element,
'is', is the shortest string in li.
Using reduce()
reduce() function from the functools module can be used to find the smallest string by length in a list. It works by iteratively applying a custom function to pairs of elements, reducing the list to a single result.
from functools import reduce
li= ['gfg', 'is', 'best', 'for', 'geeks']
# Reducing the list to the smallest string
res = reduce(lambda x, y: x if len(x) < len(y) else y, li)
print(res)
Output
is
Explanation:
reduce():Thiscompares two elements at a time using a lambda function.- lambda function: This checks the lengths of the strings and retains the smaller string.
- This process continues for all elements in the list li , comparing them one by one, and finally returns the smallest string.
Using loop
This is the brute method in which we perform this task. In this, we run a loop to keep a memory of the smallest string length and return the string with min length in list.
li = ['gfg', 'is', 'best', 'for', 'geeks']
# Initialize with a very high value
min_len = float('inf')
res = ""
# Iterate through the list
for ele in li:
if len(ele) < min_len: # Compare length with the current minimum
min_len = len(ele) # Update minimum length
res = ele # Update the result with the current smallest string
print(res)
Output
is
Explanation:
- if len(ele) < min_len: The length of the current string is compared with the current minimum length . If the current string's length is smaller, the condition is
True. - min_len = len(ele): When the condition is
True,min_lenis updated to the length of the current string.