Python Forum

Full Version: position of shortest string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!
I have to create a function that takes as a parameter a list of strings. I need my function to return a number which is the position of the string with the shortest length.
I have succesfully created the function that finds the shortest string:
def g(x):
    return min(x, key=len)
But I can't figure a second function to return the position of this string.

Note: I must not use for, while
Hello,
>>> def g(x):
	return min(x, key=len)

>>> l = ['abcd', 'ab', 'abc']
>>> l.index(g(l))
1
>>>
Example with use of walrus operator :=

def shortest_str(text_list: list[str]) -> tuple[str, int]:
    """
    Return the shortest str with index as tuple.
    """
    return (text := min(text_list, key=len)), text_list.index(text)