Skip to main content

Python Tips 01

This page keeps a "scattered but useful" style, collecting small tips that don't deserve their own full chapter but are great for quick reference later.

sorted() sorts in ascending order by default

numbers = [3, 1, 4, 1, 5, 9]

print(sorted(numbers))
print(sorted(numbers, reverse=True))

Use list.sort() for in-place sorting

numbers = [3, 1, 4]
numbers.sort()

sorted() returns a new list; sort() modifies in place.

Checking if two lists contain the same elements

If order doesn't matter:

list1 = [3, 2, 1]
list2 = [1, 2, 3]

print(sorted(list1) == sorted(list2))

If you also care about duplicate counts:

from collections import Counter

list1 = [1, 2, 2, 3]
list2 = [3, 2, 1, 2]

print(Counter(list1) == Counter(list2))

ord() and chr()

print(ord("a"))   # 97
print(chr(97)) # a

These are common in character encoding, input processing for competitive programming, and simple mapping tasks.

key= is the core of sorting

words = ["apple", "kiwi", "banana"]
print(sorted(words, key=len))

Whenever you need to sort by length, by field, or by a custom rule, think of key= first.