Skip to main content
Python provides powerful built-in data structures. This chapter covers lists in detail, plus tuples, sets, and dictionaries.

More on Lists

Lists have many useful methods:

Example Usage

Methods like insert, remove, and sort that only modify the list return None - this is a design principle for all mutable data structures in Python.

Using Lists as Stacks

Lists work well as stacks (last-in, first-out):

Using Lists as Queues

Lists are not efficient for queues (first-in, first-out) because inserts/pops from the beginning are slow. Use collections.deque instead:

List Comprehensions

List comprehensions provide a concise way to create lists:
This is equivalent to:

Complex List Comprehensions

Combine elements from two lists:
More examples:

Nested List Comprehensions

Transpose a matrix:
For complex operations, prefer built-in functions like zip():

The del Statement

Remove items from a list by index:
del can also delete entire variables:

Tuples and Sequences

A tuple consists of values separated by commas:
Tuples are immutable:
But they can contain mutable objects:

Empty and Single-Item Tuples

Tuple Packing and Unpacking

Sets

A set is an unordered collection with no duplicates:

Set Operations

Set Comprehensions

Dictionaries

Dictionaries are indexed by keys (any immutable type):

Creating Dictionaries

From sequences:
With comprehensions:
With keyword arguments:

Looping Techniques

Looping Through Dictionaries

Looping with Index

Looping Over Multiple Sequences

Looping in Reverse

Looping in Sorted Order

More on Conditions

Comparison operators can be chained:
Boolean operators and, or, and not:
Boolean operators are short-circuit: they stop evaluating as soon as the outcome is determined.

Comparing Sequences

Sequences are compared using lexicographical ordering:

Next Steps

You now understand Python’s core data structures. Next, learn how to organize code into reusable Modules.