Chapter 6. Lists and Dictionaries
This chapter presents the list and dictionary object types—collections of other objects, which are the main workhorses in almost all Python scripts. As we’ll see, both of these types are remarkably flexible: they can be changed, can grow and shrink on demand, and may contain and be nested in any other kind of object. By leveraging these types, we can build up and process arbitrarily rich information structures in our scripts.
The next stop on the built-in object tour is the Python list. Lists are Python’s most flexible ordered collection object type. Unlike strings, lists can contain any sort of object: numbers, strings, even other lists. Python lists do the work of most of the collection data structures you might have to implement manually in lower-level languages such as C. In terms of some of their main properties, Python lists are:
- Ordered collections of arbitrary objects
From a functional view, lists are just a place to collect other objects, so you can treat them as a group. Lists also define a left-to-right positional ordering of the items in the list.
- Accessed by offset
Just as with strings, you can fetch a component object out of a list by indexing the list on the object’s offset. Since items in lists are ordered by their positions, you can also do such tasks as slicing and concatenation.
- Variable length, heterogeneous, arbitrarily nestable
Unlike strings, lists can grow and shrink in place (they can have variable length), and may contain ...