Python Tuples: The Essentials
Python tuples are ordered, immutable collections that are efficient for data storage and retrieval. They support indexing, slicing, and common operations like concatenation and repetition.
Core Principles
- Tuples are defined using parentheses `()`.
- Single-element tuples require a trailing comma: `(1,)`.
- Tuples are immutable; their elements cannot be changed after creation.
- Elements are accessed using zero-based indexing.
- Slicing extracts sub-sequences using `[start:stop:step]`.
- Tuples can be traversed using loops.
- Common operations include concatenation (`+`), repetition (`*`), and membership testing (`in`).
- Built-in functions like `len()`, `sorted()`, and `sum()` are useful.
Action Steps
- Create tuples using parentheses and comma-separated elements.
- Remember the trailing comma for single-element tuples.
- Access individual elements using their index.
- Extract sub-sequences using slicing with start, stop, and step values.
- Combine tuples using the `+` operator.
- Repeat tuple elements using the `*` operator.
- Check for an element's existence using the `in` operator.
- Use `len()` to get the number of elements.
- Use `sorted()` to get a sorted list from a tuple.
- Use `sum()` for the total of numeric elements.
Formulas
- Tuple creation: `my_tuple = (element1, element2, ...)`
- Single-element tuple: `single_tuple = (element,)`
- Indexing: `element = my_tuple[index]`
- Slicing: `sub_tuple = my_tuple[start:stop:step]`
- Concatenation: `new_tuple = tuple1 + tuple2`
- Repetition: `repeated_tuple = my_tuple * n`
- Membership: `is_present = element in my_tuple`
- Length: `length = len(my_tuple)`
- Sorting: `sorted_list = sorted(my_tuple)`
- Sum: `total = sum(my_tuple)`
Key Terms
- Tuple: An ordered, immutable sequence of elements in Python.
- Immutable: Cannot be changed after creation.
- Indexing: Accessing elements by their position (starting from 0).
- Slicing: Extracting a portion (sub-sequence) of a tuple.
- Concatenation: Joining two or more tuples together.
- Repetition: Creating a new tuple by repeating the elements of an existing tuple.
- Membership: Checking if an element exists within a tuple.
Real World Examples
- Storing fixed collections of data: Representing coordinates (x, y), RGB color values (r, g, b), or database records.
- Returning multiple values from a function: Functions can return a tuple to provide several results simultaneously.
- Using as dictionary keys: Immutable tuples can be used as keys in dictionaries, unlike mutable lists.