Python: Tuples
Python Tuples
python
tuples
The file system is organized into a hierarchical structure, starting with the root directory
1 Overview
📘 Tuples in Python
A tuple in Python is an immutable ordered collection of elements used to group multiple objects into a single variable or structure. Tuples are similar to lists but are defined using parentheses () instead of square brackets [] and cannot be modified after creation.
2 Core Properties
- Tuples are defined by listing elements separated by commas, usually within parentheses, although parentheses are optional but recommended for clarity.
- Elements in a tuple are indexed, allowing access by position, and maintain the order in which they are specified.
- The immutability of tuples means their content cannot be changed after creation; no addition, deletion, or modification of elements is allowed.
- Tuples can store elements of mixed types, including other collections, functions, or objects.
- Duplicate values are allowed within tuples since each element is indexed.
2.1 Typical Usage and Behavior
- Tuples are preferred when an ordered group of items should remain constant and write-protected through the program.
- Tuple packing is the process of grouping multiple objects into a tuple, while tuple unpacking refers to the assignment of tuple elements to multiple variables at once.
- Because tuples are immutable, they are hashable and can be used as dictionary keys, unlike lists.
- Single-element tuples require a trailing comma to distinguish them from just a parenthesized expression.
2.2 Differences from Other Collections
- Unlike lists, which are mutable and offer a wider range of operations for changing contents, tuples are static after creation and support only operations that do not modify their contents.
- Tuples are one of Python’s four fundamental data structures for grouping values, with others being lists (mutable), sets (unordered, unique), and dictionaries (key/value), each suitable for different programming requirements.
Tuples serve as an efficient, predictable means for fixed groups of heterogeneous items and data integrity in Python programs.
3 Tuples
- Sequence of elements.
- Very similar to lists.
- Main difference: Tuples are immutable (size and elements cannot change).
- Pros: Immutability help prevent accidental modifications.
TypeError: ‘tuple’ object does not support item assignment
- The same rules for indexing and slicing we saw in lists can be applied to tuples.
- Because of their immutability, tuples lack a lot of the built-in methods that lists have (e.g.,
append()orsort()).
4 Usefulness
- Tuples are useful for storing elements that shouldn’t change (i.e., are fixed).
- Tuples provide safety against accidental modification of data
- Usage examples:
- Geographical coordinates: (lat, long).
- RGB colors: (255, 0, 0).
- Database rows: (‘Alice’, 30, ‘Engineer’).
- Immutable configuration of server host and port: (‘localhost’, 8080).
- 2D/3D points in space: (3, 5) or (1, 2, 3).
5 Tuples in Code
my_tuple = (1, 4, 2, 3, 2, 2)
print(f'The first element of my_tuple is {my_tuple[0]}.')
print(f'The last element of my_tuple is {my_tuple[-1]}.')
print(f'The first two elements of my_tuple are {my_tuple[:2]}.')
print(f'The length of my_tuple is {len(my_tuple)}.')
print(f'The number of 2s in my_tuple is {my_tuple.count(2)}.')
print(f'The sum of my_tuple is {sum(my_tuple)}.')
The first element of my_tuple is 1.
The last element of my_tuple is 2.
The first two elements of my_tuple are (1, 4).
The length of my_tuple is 6.
The number of 2s in my_tuple is 3.
The sum of my_tuple is 14.
The last element of my_tuple is 2.
The first two elements of my_tuple are (1, 4).
The length of my_tuple is 6.
The number of 2s in my_tuple is 3.
The sum of my_tuple is 14.
- Multi-type tuples:
- Convert lists to tuples and vice versa:
6 Operations
- Like lists, concatenation with the
+operator and repetition with the*operator.
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
True
False
False
False
False
---
## `in`
- Like lists, check if an element is inside a tuple:
```python
print(3 in (1, 3, 2, 1))
True
False
7 Iteration
- Same as lists:
1
2
3
2
3
8 zip
- Combines multiple iterables (like lists or tuples) element-wise.
- Given
iterable1anditerable2, it returns tuples where the first item is fromiterable1and the second is fromiterable2. - If the input iterables are of uneven length, zip stops creating pairs when the shortest iterable is exhausted.
[(1, 4), (2, 5), (3, 6)]
1 4
2 5
3 6
2 5
3 6
- Practical example:
Alice: 8.5
Bob: 9.2
Charlie: 7.8
David: 9.0
Bob: 9.2
Charlie: 7.8
David: 9.0
9 Comprehension
- Sequence comprehension for creating new tuples:
(0, 2, 4, 6, 8)
This code creates a tuple containing even numbers from 0 up to 8 by multiplying each number in the range 0 to 4 (inclusive) by 2, and then prints the tuple.
- How the Code Works:
range(5)produces the sequence 0, 1, 2, 3, 4.- The generator expression
i * 2 for i in range(5)calculates 0, 2, 4, 6, and 8. - The
tuple()function collects these values into a tuple: (0, 2, 4, 6, 8). print(even_tuple)outputs this tuple.