2. Lists and Dictionaries¶
Many programs are written to automate repetitive tasks that are better suited to machines than to humans. In Python, the most common way to organize this kind of work is by using a sequence of values stored in a list type. Lists are extremely versatile and can be used to solve a variety of problems.
A natural complement to lists is the dict type, which stores lookup keys mapped to corresponding values (in what is often called an associative array or a hash table). Dictionaries provide constant time (amortized) performance for assignments and accesses, which means they are ideal for bookkeeping dynamic information.
Python has special syntax and built-in modules that enhance readability and extend the capabilities of lists and dictionaries beyond what you might expect from simple array, vector, and hash table types in other languages.
- 2.1. Know How to Slice Sequences
- 2.2. Avoid Striding and Slicing in a Single Expression
- 2.3. Prefer Catch-All Unpacking Over Slicing
- 2.4. Sort by Complex Criteria Using the key Parameter
- 2.5. Be Cautious When Relying on dict Insertion Ordering
- 2.6. Prefer get Over in and KeyError to Handle Missing Dictionary Keys
- 2.7. Prefer defaultdict Over setdefault to Handle Missing Items in Internal State
- 2.8. Know How to Construct Key-Dependent Default Values with __missing__