225k views
3 votes
Question:

Ask the user to enter 10 names and store it in a list and now sort it based on the longest name(the length of the name ) , such a way that the shortest name comes first the longest name comes at the last.

I have tried looking up elsewhere, but nothing seems to help. My current code is:
x=input("Input ten names:")

nums= list((input().split()))
nums.sort()
print("After sorting names:")
print(*nums)

User J Ng
by
8.0k points

2 Answers

2 votes

Sure, I can help you with that. Here's some code that should do what you're looking for:

# Ask the user to input 10 names and store them in a list

names = []

for i in range(10):

name = input("Enter a name: ")

names.append(name)

# Sort the list based on the length of each name

names.sort(key=len)

# Print the sorted list

print("Sorted names (shortest to longest):")

for name in names:

print(name)

This code prompts the user to enter 10 names, stores them in a list, and then sorts the list based on the length of each name. The key=len argument tells the sort function to sort based on the length of each string instead of the default lexicographic order.


This shoud be sufficient, thanks!

- Eddie E.

User Memedon
by
8.1k points
4 votes
names = []
for i in range(0, 9):
n = input("Enter a name: ")
names.append(n)
print(sorted(names, key=len))


This code should work
User Alexis Leclerc
by
7.9k points

No related questions found