Skip to content

Informatics Practices · Ch 4 — Working with Lists and Dictionaries

Summary

Summary

  • Lists are mutable sequences in Python — the elements of a list can be changed after it is created.
  • A list is written by placing its elements inside square brackets, separated by commas, e.g. [10, 20, 30].
  • List indexing starts at 0. Python allows two-way indexing: forward with indices 0, 1, 2, … and backward with negative indices, so a list can be traversed in either direction.
  • The + operator concatenates one list to the end of another; the * operator repeats the contents of a list the specified number of times.
  • The membership operator in tests whether an element is present in a list, and not in tests the opposite.
  • Slicing extracts a part of a list using the list[start:stop:step] form.
  • Lists come with many manipulation methods and functions, including len(), list(), append() (add one element at the end), extend() (add all elements of another list), insert(), count(), index(), remove(), pop(), reverse(), sort(), sorted(), min(), max() and sum().
  • append() adds its argument as a single element, while extend() adds each element of its argument individually; sort() changes the list itself, while sorted() returns a new sorted list leaving the original untouched.
  • A dictionary is a mapping (non-scalar) data type: an unordered collection of key-value pairs written inside curly braces.
  • Each key is separated from its value by a colon, and consecutive pairs are separated by commas, e.g. {'Mohan': 95, 'Ram': 89}.
  • Keys are unique and act as the index used to access values; keys must be of an immutable type, while values can be mutable.
  • A dictionary is traversed with a for loop — either looping over the dictionary itself (which yields keys, with values fetched as d[key]) or looping over d.items() (which yields each key-value pair directly). …