Python Forum
position of shortest string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
position of shortest string
#1
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
Yoriz write Mar-17-2022, 12:48 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Hello,
>>> def g(x):
	return min(x, key=len)

>>> l = ['abcd', 'ab', 'abc']
>>> l.index(g(l))
1
>>>
I speak Python but I don't speak English (I just read it a little). If I express myself badly, please blame the translator^^.
Reply
#3
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)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Shortest path from s to t using python nkiki 9 768 Jan-28-2024, 05:58 PM
Last Post: Gribouillis
  Finding and storing all string with character A at middle position Pippi 2 2,698 Jan-20-2019, 08:23 AM
Last Post: Pippi
  Python Shortest Path python_snake 1 4,411 Mar-14-2017, 06:36 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020