Python Tutorial

Python Sort Lists

sort() orders the list in place. reverse() flips the current order. sorted() returns a new list.

sort() and reverse()

Alphanumeric, ascending by default. Case-sensitive: capitals come before lowercase.

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
thislist.sort(reverse=True)
print(thislist)

Custom Key

Pass a function as key. Use str.lower to ignore case.

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key=str.lower)
print(thislist)
print(sorted([3, 1, 2]))

📘 Real-World Deep Dive

Sorting is the operation people code from scratch. Knowing <code>list.sort</code>, <code>sorted</code>, <code>key=</code>, and <code>functools.cmp_to_key</code> turns "sort by revenue desc with tiebreaker" into 1 line.

Real-Life Scenario

Sort a list of orders by multiple keys (status > total > date) and keep the original list unfrozen for follow-on edits.

Real-Life Example

from dataclasses import dataclass
from datetime import date

@dataclass
class Order:
    oid: int
    total: float
    status: str
    placed: date

orders = [
    Order(1, 120.0, "paid",   date(2026, 8, 19)),
    Order(2,  25.0, "draft",  date(2026, 8, 21)),
    Order(3, 120.0, "paid",   date(2026, 8, 17)),
    Order(4, 300.0, "refund", date(2026, 8, 22)),
    Order(5, 300.0, "paid",   date(2026, 8, 20)),
]

STATUS_ORDER = {"paid": 0, "draft": 1, "refund": 2}

ranked = sorted(
    orders,
    key=lambda o: (STATUS_ORDER[o.status],                 # primary
                  -o.total,                                # secondary: desc
                  o.placed),                               # tertiary: asc
)
for o in ranked:
    print(o)

Expected Output

Order(oid=5, total=300.0, status='paid', placed=datetime.date(2026, 8, 20))
Order(oid=1, total=120.0, status='paid', placed=datetime.date(2026, 8, 19))
Order(oid=3, total=120.0, status='paid', placed=datetime.date(2026, 8, 17))
Order(oid=2, total=25.0, status='draft', placed=datetime.date(2026, 8, 21))
Order(oid=4, total=300.0, status='refund', placed=datetime.date(2026, 8, 22))

Common mistakes

  • list.sort() returns None — assigning the result is a common silent bug.
  • Tuple comparator keys: tuples compare element-by-element but Python types differ — don't mix str and int.
  • Numeric "reversed" sort needs negation; only since Python 3 you can write reverse=True instead.

🚀 Performance & Best Practices

  • Pre-compute keys once with items.sort(key=lambda x: (rank[x.id], x.score)) — the key fn runs fewer times.
  • operator.attrgetter / itemgetter beat lambdas in micro-benchmarks.
  • For huge lists, consider numpy.argsort + vectorized gather.

🧪 Try It Yourself

  1. Refactor ranked to use attrgetter on a frozen dataclass.
  2. Sort the same list by stringified date and benchmark both.
  3. Write a comparator that handles missing values (treat None as "always last").

FAQ: Python Sort Lists

Common questions about this page.

What is Python Sort Lists?

Python Sort Lists is a Python Tutorial lesson that explains sort list python in Python. sort() orders the list in place. reverse() flips the current order. sorted() returns a new list. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run sort list python examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn sort list python in this Python Tutorial Python lesson (Python Sort Lists).

How do I use sort list python in Python?

To use sort list python in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of sort list python?

This Python Sort Lists tutorial shows sort list python syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Sort Lists example for beginners

Yes. This page includes a beginner sort list python example you can copy and run. It is designed for searches such as "sort list python for beginners", "sort list python example", and "how to use sort list python".

What are common mistakes with sort list python?

Common sort list python mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn sort list python?

Python Sort Lists is used in real Python work. Learning sort list python helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Sort Lists free to learn online?

Yes. You can learn sort list python free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.