-2

I have a list of numbers in Python and I’m trying to sort them in ascending order. Here’s my code:

numbers = [5, 2, 1, 8, 4]

I tried using the sort() function like this: sort(numbers), but I get an error that says name 'sort' is not defined. What am I doing wrong and how can I sort my list?

4
  • numbers.sort() Commented Dec 1, 2023 at 13:36
  • 1
    You may want to familiarize yourself with the Python documentation. The function is called sorted. Alternatively, you could use the sort method of the list. Read the documentation to find out about the difference between those two approaches. Commented Dec 1, 2023 at 13:36
  • 1
    You should look up the difference between functions and methods. Commented Dec 1, 2023 at 13:38
  • Does this answer your question? Sort a list in python Commented Dec 5, 2023 at 0:23

1 Answer 1

1

First of all, when you ask a question try to be as descriptive as possible regarding your problem. A part from the input you are using, here you should add the whole code and also the error message if possible.

Okay!, let's go to the question. Note that sort() is a method of the list class, and it affects the original list you are calling this method on, because it runs in-place (aka returns None). Therefore the syntax (without any additional arguments) would be:

numbers.sort()

This approach is slightly more efficient.

On the other side, if you want to use the built-in function sorted(), you need to assign it to a new variable, as this function creates a new list from the original one, for example:

numbers_sorted = sorted(numbers)

Check this for more examples.

Hope it is clear enough!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.