Skip to content

Computer Science · Ch 9 — Lists

Summary

Summary

  • Lists are mutable sequences in Python — the elements of a list can be changed after the list is created.
  • The elements of a list are written inside square brackets, separated by commas; they may be of mixed data types (integers, floats, strings, tuples, even other lists).
  • A list appearing inside another list is a nested list.
  • List indexing works like string indexing and starts at 0. Two-way indexing lets you traverse a list forward (0, 1, 2, …) or backward with negative indices (-1 is the last element). An out-of-range index raises IndexError.
  • The + operator concatenates one list to the end of another, producing a new list; both operands must be lists, and the originals are unchanged unless the result is assigned.
  • The * operator repeats a list a specified number of times.
  • The membership operator in tells whether an element is present in a list; not in does the opposite.
  • Slicing (list[start:stop:step]) extracts a part of a list; missing indices default to the ends, an oversized stop truncates, and [::-1] yields the reversed list.
  • A list can be traversed with a for loop (directly over elements, or over indices via range(len())) or with a while loop and a counter.
  • Many list manipulation functions and methods are available, including: len(), list(), append(), extend(), insert(), count(), index(), remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum(). Remember index()/remove() raise ValueError for a missing element, sort()/reverse() work in place, and sorted() returns a new list.
  • An element inside a nested list is reached with two indices: list[i][j]. …