Content · Programming · Python

Python sorted() Function: Usage and Examples

sorted(iterable, key=None, reverse=False) returns a new list in sorted order, leaving the original iterable unchanged. The optional key function supplies one comparison value per element. See two practical examples.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A report displays product labels alphabetically while preserving input order.

What You Need to Understand


sorted(iterable, key=None, reverse=False) returns a new list in sorted order, leaving the original iterable unchanged. The optional key function supplies one comparison value per element.

When to Use It


A report displays product labels alphabetically while preserving input order.

Step-by-Step Python Example


products = ["pear", "Apple", "banana"]
print(sorted(products))
print(sorted(products, key=str.casefold))
print(products)

How the Example Works


Default text sorting is case-sensitive; key=str.casefold provides a more useful case-insensitive order for this simple example.

Example Output


['Apple', 'banana', 'pear']
['Apple', 'banana', 'pear']
['pear', 'Apple', 'banana']
[91, 84, 72]

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

scores = [72, 91, 84]
print(sorted(scores, reverse=True))

Important Behavior and Edge Cases


sorted() needs mutually comparable key values. Sorting text case-insensitively is not a complete locale-aware alphabetical collation.

Try It Yourself


Sort numerical scores descending and verify the source list remains unchanged.

Common Beginner Mistakes


  • sorted() needs mutually comparable key values. Sorting text case-insensitively is not a complete locale-aware alphabetical collation.
  • Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.

Key Takeaways


  • sorted(iterable, key=None, reverse=False) returns a new list in sorted order, leaving the original iterable unchanged.
  • Default text sorting is case-sensitive; key=str.casefold provides a more useful case-insensitive order for this simple example.
  • sorted() needs mutually comparable key values.
Share this resourceSend this page to someone who may find it useful.