indusai.co

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.

python
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 insensitive

The key argument accepts any function; the list is sorted by the values that function returns.

python
students = [("Riya", 88), ("Arjun", 95), ("Meera", 79)]
by_marks = sorted(students, key=lambda s: s[1], reverse=True)
print(by_marks)

Reversing

python
nums = [1, 2, 3]
nums.reverse()
print(nums)
print(nums[::-1])   # reversed copy, original unchanged

Copying a list

Assigning a list to a new name does not copy it. Both names point at the same list.

python
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:

python
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.

python
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].

python
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:

python
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:

python
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(labels)

Unpacking with *

python
first, *rest = [1, 2, 3, 4]
print(first, rest)

*init, last = [1, 2, 3, 4]
print(init, last)

Practice

  1. Sort ["Delhi", "mumbai", "Bengaluru", "chennai"] alphabetically ignoring case.
  2. Use a comprehension to make a list of the lengths of each word in "the quick brown fox".split().
  3. Create a 3 by 3 grid of zeros with a comprehension, then set the centre cell to 1 and print each row.