Python List Examples
A runnable cookbook of everyday Python list tasks — sum, unique, flatten, filter, group and more — each a short snippet you can run in the browser.
Overview
Short, copy-paste examples for the most common things you do with lists in Python. Run any of them in the online Python compiler.
Examples
Sum and average
nums = [10, 20, 30, 40]
total = sum(nums) # 100
average = sum(nums) / len(nums) # 25.0
Largest and smallest
nums = [3, 7, 2, 9, 4]
print(max(nums), min(nums)) # 9 2
Unique values (keeping order)
items = [1, 1, 2, 3, 3, 3]
unique = list(dict.fromkeys(items)) # [1, 2, 3] — order preserved
unique_unordered = list(set(items)) # also unique, but order not guaranteed
Filter and transform (comprehension)
nums = [1, 2, 3, 4, 5, 6]
doubled_evens = [n * 2 for n in nums if n % 2 == 0]
print(doubled_evens) # [4, 8, 12]
Flatten a nested list
matrix = [[1, 2], [3, 4], [5]]
flat = [x for row in matrix for x in row]
print(flat) # [1, 2, 3, 4, 5]
Any / all / find
nums = [1, 2, 3]
print(any(n > 2 for n in nums)) # True
print(all(n > 0 for n in nums)) # True
print(next((n for n in nums if n == 2), None)) # 2 (first match, else None)
Count occurrences
from collections import Counter
votes = ["a", "b", "a", "c", "b", "a"]
counts = Counter(votes)
print(counts["a"]) # 3
print(counts.most_common(1)) # [('a', 3)]
Join a list into a string
words = ["a", "b", "c"]
print(", ".join(words)) # a, b, c
Sort a copy (leave the original alone)
nums = [10, 1, 21, 2]
print(sorted(nums)) # [1, 2, 10, 21] — see the how-to for key= and reverse=
Frequently asked questions
How do I sum a list of numbers in Python?
Use the built-in
sum(my_list). For an average, divide by len(my_list).How do I get unique values from a list?
list(dict.fromkeys(items)) keeps the original order; list(set(items)) is shorter but does not guarantee order.How do I flatten a nested list?
Use a nested comprehension:
[x for row in matrix for x in row].