Open links in new tab
    • Work Report
    • Email
    • Rewrite
    • Speech
    • Title Generator
    • Smart Reply
    • Poem
    • Essay
    • Joke
    • Instagram Post
    • X Post
    • Facebook Post
    • Story
    • Cover Letter
    • Resume
    • Job Description
    • Recommendation Letter
    • Resignation Letter
    • Invitation Letter
    • Greeting Message
    • Try more templates
  1. In Python, you can sort a list using the sorted() function or the sort() method. The sorted() function returns a new sorted list, while the sort() method sorts the list in place.

    Example: Using sorted()

    numbers = [6, 9, 3, 1]
    sorted_numbers = sorted(numbers)
    print(sorted_numbers) # Output: [1, 3, 6, 9]
    print(numbers) # Output: [6, 9, 3, 1]
    Copied!

    Example: Using sort()

    numbers = [6, 9, 3, 1]
    numbers.sort()
    print(numbers) # Output: [1, 3, 6, 9]
    Copied!

    Key Differences:

    • sorted(): Returns a new sorted list and does not modify the original list.

    • sort(): Modifies the original list in place and returns None.

    Sorting with Custom Key:

    You can use the key parameter to specify a function to be called on each list element prior to making comparisons.

    words = ["banana", "pie", "Washington", "book"]
    sorted_words = sorted(words, key=len)
    print(sorted_words) # Output: ['pie', 'book', 'banana', 'Washington']
    Copied!

    Sorting in Reverse Order:

    Both sorted() and sort() accept a reverse parameter to sort in descending order.

    Feedback
  2. Sorting Algorithms in Python - GeeksforGeeks

    Dec 12, 2025 · It was Created by Tim Peters in 2002, Tim Sort is the default sorting algorithm in Python and is renowned for its speed and efficiency in real-world …

  3. Python List sort () Method - W3Schools

    Definition and Usage The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria (s).

    Code sample

    # Sort the list alphabetically
    cars = ['Ford', 'BMW', 'Volvo']
    cars.sort()
  4. How to Use sorted() and .sort() in Python – Real Python

    May 6, 2019 · In this tutorial, you’ll learn how to sort various types of data in different data structures, customize the order, and work with two different ways …

  5. How To Sort An Array In Python?

    Dec 23, 2024 · Learn how to sort arrays in Python using built-in methods like sort () and sorted (), and explore custom sorting with lambda functions in this easy-to-follow guide