-2

I want to create/call a function that first sorts a list of strings, and then then displays each item on the list, one per line in sorted & numerical order.

# This is an incomplete function
list = ["Hello", "Friend", "Apple", "Banana"]
def sorted()
    sortedlist = sorted(list)
    for i in sortedlist:
        print (i)

The end result would look like this:

  1. Apple
  2. Banana
  3. Friend
  4. Hello

I suppose that once the list is sorted, then concat a 1, 2, 3 and so on for each item in the list, and then print?

  • 1
    That's a requirement, not a programming question. What have you done, and what problems did you run into in the process? – Mad Physicist Oct 28 '19 at 02:56
  • name `list` something else so as not to shadow the built-in `list`, then do `print(list(enumerate(my_list)))`? – Green Cloak Guy Oct 28 '19 at 03:01
  • Don't use the function name `sorted()` as that's actually a built-in function in Python. If you remove your definition (or rename it) and do `sorted(array)` you will notice it will actually return the sorted list. – felipe Oct 28 '19 at 03:01
  • The enumerate functions looks like the way to go once the list is sorted, thank you! I will also avoid using the built-in function. –  Oct 28 '19 at 03:04
  • To more directly answer your question, you want two functions: (1) One that will actually sort and return the sorted array. (2) One that will print your array. The print portion (#2) you have it right with the `for-loop` but as @GreenClockGuy mentioned, enumerate would work best for your goal; for the sorting portion (#1) it's no bueno. If you want to create your own custom sorting function, check out this resource [here](https://www.youtube.com/playlist?list=PLEJyjB1oGzx2h88Tj90B5_HadLq339Cso). – felipe Oct 28 '19 at 03:05
  • Possible duplicate of [Does Python have a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – Gurupad Hegde Oct 28 '19 at 08:10

1 Answers1

1

A quick way to do this is with enumerate which generates a tuple for each element in the list, the first element being the label, the second being the item itself. If you want to start at 1:

sortedlist = sorted(list)

for i in enumerate(sortedlist, start=1):
    print(f"{i[0]}. {i[1]}")
neutrino_logic
  • 1,289
  • 1
  • 6
  • 11