Chapter 8. Lists and Dictionaries
Now that we’ve explored numbers and strings, this chapter moves on to give the full story on Python’s list and dictionary objects—collections of other objects, and the main workhorses in almost all Python scripts. As you’ll find, both are remarkably flexible: they can be changed in place, can grow and shrink on demand, and may contain and be nested in any other kind of object. By leveraging these built-in object types, you can create and process rich information structures in your scripts without having to define new object types of your own.
Lists
The first stop on this chapter’s 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, and even other lists. Also, unlike strings, lists may be changed in place by assignment to offsets and slices, list method calls, deletion statements, and more—they are mutable objects.
Python lists do the work of many of the collection data structures you might have to implement manually in lower-level languages such as C. Here is a quick look at their main properties. Python lists are:
- Ordered collections of arbitrary objects
- From a functional view, lists are just places to collect other objects so you can treat them as groups. Lists also maintain a left-to-right positional ordering among the items they contain.
- Accessed by offset
- Just as with strings, you can fetch a component object from a list by indexing ...