Home > Enterprise >  How to write the correct code: sort a list in alphabetical order within a function?
How to write the correct code: sort a list in alphabetical order within a function?

Time:10-18

I need to write a code where my output is a grocery list in alphabetical order

This is my code right now:

def alphabetical_order():

  return list

alphabetical_order = ["cherry", "orange", "apple", "banana"]

alphabetical_order.sort()
print(alphabetical_order)

Output is: ['apple', 'banana', 'cherry', 'orange']

My output is correct, but is this done the correct way or am I missing something?

CodePudding user response:

You don't need a function to sort a list on python.

You just have to use .sort() method like this:

myList = ["cherry", "orange", "apple", "banana"]
myList.sort() # Will set myList as a sorted list.

print(myList) # ['apple', 'banana', 'cherry', 'orange']

Moreover, take care to don't use the same name for a variable and a function. Each thing must have its own name.

CodePudding user response:

You have't called the alphabetical_order(): function if you want to sort it within the function then it should be like this

def alphabetical_order():
   alphabetical_order = ["cherry", "orange", "apple", "banana"]
   alphabetical_order.sort()      #sorting List
   print(alphabetical_order)

#function call   
alphabetical_order()
  • Related