Python Data Structures: Tuples, Sets, Dictionaries, and Lists
This cheat sheet covers the fundamental Python data structures: tuples, sets, dictionaries, and lists, detailing their properties, operations, and common use cases.
Core Principles
- Tuples: Immutable, ordered sequences, defined with parentheses (). Useful for fixed collections.
- Sets: Unordered collections of unique elements, defined with curly braces {}. Ideal for membership testing and removing duplicates.
- Dictionaries: Key-value pairs, unordered (prior to Python 3.7), defined with curly braces {}. Used for mapping unique keys to values.
- Lists: Mutable, ordered sequences, defined with square brackets []. Highly versatile for dynamic data storage.
- Mutability: Tuples are immutable (cannot be changed after creation), while lists and dictionaries are mutable.
- Indexing: Tuples and lists support indexing to access elements by position. Dictionaries use keys for access.
- Uniqueness: Sets store only unique elements. Dictionaries require unique keys.
- Order: Tuples and lists maintain insertion order. Sets do not guarantee order.
- Operations: Each data structure supports specific operations like append, insert, remove, add, and iteration.
- Use Cases: Choose the appropriate structure based on whether data needs to be ordered, unique, mutable, or mapped.
Key Terms
- Immutable: An object whose state cannot be modified after it is created.
- Mutable: An object whose state can be modified after it is created.
- Ordered Sequence: A collection where elements have a defined order and can be accessed by their position (index).
- Unordered Collection: A collection where elements do not have a defined order.
- Key-Value Pair: A mapping in a dictionary where a unique key is associated with a specific value.
- Set: An unordered collection of unique elements, used for membership testing and eliminating duplicates.
- Tuple: An immutable, ordered sequence, often used for fixed collections of items.
- Dictionary: A mutable collection of key-value pairs, used for mapping and fast lookups.
- List: A mutable, ordered sequence, highly versatile for storing and manipulating data.
Real World Examples
- Storing course information (ID, Name, Duration): Tuples are suitable as this data is fixed and should not change.
- Tracking student registrations: Lists are used as new students are added continuously.
- Mapping students to courses: Dictionaries provide a clear mapping from student names (keys) to course tuples (values).
- Tracking attendance per student: Dictionaries with lists as values allow tracking multiple session numbers for each student.
- Collecting unique artifacts: Sets are ideal for storing unique items and automatically handle duplicates.
- Storing historical records that must not be altered: Tuples ensure data integrity due to their immutability.