Python Tutorial · Data Structures · Lesson 15 of 42
Python List Methods and Comprehensions
Sort, search and transform lists — and write list comprehensions.
Useful list methods
nums = [3, 1, 4, 1, 5, 9, 2]
print(sorted(nums))
nums.sort(reverse=True)
print(nums)
print(nums.index(4), nums.count(1))
print(min(nums), max(nums), sum(nums))
Output
[1, 1, 2, 3, 4, 5, 9] [9, 5, 4, 3, 2, 1, 1] 2 2 1 9 25
sort() changes the list in place; sorted() returns a new list and works on any iterable.
Sorting with a key
words = ["banana", "Apple", "cherry"]
print(sorted(words))
print(sorted(words, key=str.lower))
print(sorted(words, key=len))
people = [("Ana", 31), ("Bo", 25)]
print(sorted(people, key=lambda p: p[1]))
Output
['Apple', 'banana', 'cherry']
['Apple', 'banana', 'cherry']
['Apple', 'banana', 'cherry']
[('Bo', 25), ('Ana', 31)]List comprehensions
A comprehension builds a new list from an iterable in one readable line: [expression for item in iterable if condition].
nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums]
evens = [n for n in nums if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(squares)
print(evens)
print(labels)
Output
[1, 4, 9, 16, 25, 36] [2, 4, 6] ['odd', 'even', 'odd', 'even', 'odd', 'even']
Comprehensions are usually clearer than map()/filter() with lambdas — but if one gets long, use a normal loop.
Test yourself
What does [x * 2 for x in [1, 2, 3] if x > 1] produce?
[2, 4, 6][4, 6][1, 2, 3][2, 4]
Show answer
Answer: [4, 6]