Working with lists
This lesson covers what you do with lists once you have them: sorting, copying, nesting and the compact list comprehension syntax that experienced Python programmers use everywhere.
Sorting
sort() sorts a list in place. sorted() returns a new sorted list and leaves the original alone. Both work on any list of comparable items.
nums = [3, 1, 4, 1, 5]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)
words = ["banana", "Apple", "cherry"]
print(sorted(words)) # capitals sort first
print(sorted(words, key=str.lower)) # case insensitiveThe key argument accepts any function; the list is sorted by the values that function returns.
students = [("Riya", 88), ("Arjun", 95), ("Meera", 79)]
by_marks = sorted(students, key=lambda s: s[1], reverse=True)
print(by_marks)Reversing
nums = [1, 2, 3]
nums.reverse()
print(nums)
print(nums[::-1]) # reversed copy, original unchangedCopying a list
Assigning a list to a new name does not copy it. Both names point at the same list.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # a changed too!To make an independent copy use copy(), list() or a full slice:
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a, b)These are shallow copies: nested lists inside are still shared. For a fully independent copy use copy.deepcopy().
Nested lists
A list can contain lists. This is how you represent grids and tables.
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(grid[1][2]) # row 1, column 2
for row in grid:
print(row)List comprehensions
A comprehension builds a new list from an iterable in one expression. The pattern is [expression for item in iterable if condition].
squares = [n ** 2 for n in range(6)]
print(squares)
evens = [n for n in range(20) if n % 2 == 0]
print(evens)
upper = [w.upper() for w in ["a", "b", "c"]]
print(upper)Compare to the loop version:
squares = []
for n in range(6):
squares.append(n ** 2)
print(squares)Comprehensions are shorter, usually faster and, once you are used to them, clearer. Keep them to one line of logic; if you need nested conditions, write a loop.
An if else inside the expression chooses between two values:
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(labels)Unpacking with *
first, *rest = [1, 2, 3, 4]
print(first, rest)
*init, last = [1, 2, 3, 4]
print(init, last)Practice
- Sort
["Delhi", "mumbai", "Bengaluru", "chennai"]alphabetically ignoring case. - Use a comprehension to make a list of the lengths of each word in
"the quick brown fox".split(). - Create a 3 by 3 grid of zeros with a comprehension, then set the centre cell to 1 and print each row.
