6 Python Collections

Learn how Python lists, tuples, dictionaries, sets, indexing, slicing, references, and iteration work, and how to choose the right collection for a task.

Choosing the right collection

Python collections group multiple values so that a program can store, retrieve, and process related data. The main built-in choices differ in order, mutability, uniqueness, and lookup style.

  • Choose a when order matters and the contents may change.

  • Choose a for a fixed group of related values.

  • Choose a when values should be found through meaningful keys.

  • Choose a when unique values and membership tests matter more than position.

A useful first question is whether the program needs positional access, key-based access, or uniqueness. A second question is whether the collection itself must change after creation.

Takeaway: Select the collection based on the behavior the data needs, not merely on the number of values it contains.

Lists and concise transformations

A preserves the order in which its elements are stored and can be changed after creation. Common operations add one item, add several items, insert before a position, remove a matching value, remove and return an item, sort the values, reverse the order, and count the elements.

The in operator tests whether a value is present. Removing a value that is absent raises ValueError, while removing an item from an invalid position or an empty with pop() raises IndexError.

A is a concise way to transform or filter an iterable. For example, squares = [n * n for n in range(1, 6)] produces the squares of the integers from 11 through 55. A regular loop is clearer when the logic is complex or requires several statements.

Takeaway: Lists are flexible ordered containers; use their methods for direct changes and comprehensions for simple transformations.

Tuples, positions, and unpacking

A is ordered like a but cannot have its own elements replaced or deleted. Commas create tuples, so a one-item needs a trailing comma, as in (42,); (42) is just a parenthesized value.

Tuples are useful for fixed structures such as a point or a record. Unpacking assigns elements to separate variables, and extended unpacking can collect several middle elements into a . A can contain a mutable object, such as a ; the 's position remains fixed, but the inner can still change.

applies to both lists and tuples. The first item is at index 00, and a negative index counts from the end, so -1 identifies the last item. Assigning through an index is valid for a but raises TypeError for a .

Takeaway: Use a when the structure should remain fixed, and a when its elements need to be reassigned or resized.

, copying, and references

selects a range from a sequence with start:stop:step. The start position is included and the stop position is excluded. For example, numbers[1:4] selects the elements at positions 11, 22, and 33; omitted boundaries select from the beginning or through the end, and a negative step can reverse a sequence.

For lists, a slice creates a new outer . This is a , so appending to the new does not change the original 's length, but changes to a shared nested are visible through both collections. Slice assignment can replace, insert, or delete several elements. The step cannot be zero, and extended slice replacement must satisfy additional length requirements.

Assignment normally creates another reference to the same object rather than a copy. If second refers to first, changing second also changes first. Use , .copy(), or a constructor for a ; use deepcopy() from the copy module when nested objects must be copied recursively.

Takeaway: Distinguish a new outer container from independent nested data before modifying a collection.

Iteration, mappings, and unique values

Collections are iterable when they can provide their elements one at a time to a for loop. Use enumerate() when both an index and a value are needed, and use zip() to process related collections in parallel.

Dictionaries iterate over keys by default. The .items(), .keys(), and .values() methods make the intended part of the explicit. Avoid changing a collection's size while iterating over it; instead, iterate over a copy or construct a new collection, such as a filtered .

A maps unique keys to values. Assigning to an existing key replaces its value, while assigning to a new key adds a pair. .get() supplies a fallback when a key may be absent and avoids KeyError. comprehensions construct mappings concisely.

A stores unique values and supports membership tests without positional indexing. Its operators express union, intersection, difference, and symmetric difference. frozenset() provides an immutable, when a must be used as a key or as an element of another .

Takeaway: Iteration expresses how data is processed, dictionaries express key-based relationships, and sets express uniqueness and algebra.