Python Tuples: The Essentials
Python tuples are ordered, immutable collections that can be created, accessed, and manipulated using various operators and built-in functions. They are fundamental for storing related data that should not change.
Core Principles
- Tuples are defined using parentheses `()`.
- Single-element tuples require a trailing comma: `(1,)`.
- Tuples are immutable, meaning their elements cannot be changed after creation.
- Elements are accessed via zero-based indexing.
- Slicing extracts sub-sequences of a tuple.
- Tuples support concatenation, repetition, and membership testing.
Action Steps
- Create a tuple by enclosing comma-separated elements in parentheses.
- Access individual elements using their index: `my_tuple[index]`.
- Extract a range of elements using slicing: `my_tuple[start:stop:step]`.
- Combine tuples using the `+` operator.
- Repeat a tuple using the `*` operator.
- Check for an element's presence using the `in` keyword.
- Iterate through tuple elements using a `for` loop.
- Use `len()` to get the number of elements.
- Use `sorted()` to get a new sorted list from a tuple.
- Use `sum()` to calculate the total of numeric elements.
Key Terms
- Tuple: An ordered, immutable collection of Python objects.
- Immutable: Cannot be changed after creation.
- Indexing: Accessing elements by their position (starting from 0).
- Slicing: Extracting a portion of a tuple.
- Concatenation: Joining two or more tuples together.
- Repetition: Creating a new tuple by repeating an existing one.
- Membership: Checking if an element exists within a tuple.
Real World Examples
- Storing fixed coordinates (e.g., latitude, longitude).: Tuples ensure coordinates are not accidentally modified.
- Returning multiple values from a function.: Functions can return a tuple of results.
- Using data as dictionary keys.: Tuples are hashable and can be used as dictionary keys, unlike lists.