4.3 - Working With Tuples
A tuple is a collection of Python objects separated by commas. In some ways, tuples are similar to lists, but they are enclosed in parentheses (...)
. Tuples can contain a mix of different data types and can be nested.
Tuples are immutable, meaning that once a tuple is created, its values cannot be changed, added, or removed. This immutability makes tuples a safer choice for write-protected data. They support duplicate elements and mixed data types.
4.3.1 - Creating Tuples
Tuples are defined by enclosing elements in parentheses ()
:
# An empty tuple
empty_tuple = ()
# A tuple with mixed types
mixed_tuple = (1, "hello", 3.14, True)
# A single element tuple (note the comma)
single_element_tuple = (1,)
4.3.2 - Accessing Tuple Elements
Tuple elements can be accessed by their index:
my_tuple = (10, 20, 30, 40, 50)
# Accessing the first element
first_element = my_tuple[0]
# Accessing the last element using negative indexing
last_element = my_tuple[-1]
4.3.3 - Slicing Tuples
Similar to lists, tuples can be sliced to obtain a subset:
# Getting the first three elements
first_three = my_tuple[:3]
# Getting elements from 2nd to 4th position
slice_middle = my_tuple[1:4]
# Getting the last two elements
last_two = my_tuple[-2:]
4.3.4 - Tuple Length
The len()
function is used to get the number of elements in a tuple:
length = len(my_tuple)
4.3.5 - Checking if an Item Exists in a Tuple
To check if an item exists in a tuple, use the in
keyword:
if 20 in my_tuple:
print("20 is in the tuple")
4.3.6 - Iterating Over Tuples
Iterate over the elements of a tuple using a for loop:
for element in my_tuple:
print(element)
4.3.7 - Tuple Concatenation and Repetition
Tuples can be concatenated and repeated using +
and *
operators:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Concatenation
concatenated = tuple1 + tuple2 # (1, 2, 3, 4, 5, 6)
# Repetition
repeated = tuple1 * 3 # (1, 2, 3, 1, 2, 3, 1, 2, 3)
4.3.8 - Tuple Indexing and Counting
.index(element)
: Returns the index of the first occurrence of the element..count(element)
: Returns the count of how many times an element occurs in a tuple.
Example:
print(my_tuple.index(30)) # 2
print(my_tuple.count(20)) # 1
4.3.9 - Nested Tuples
Tuples can contain other tuples, forming nested structures:
nested_tuple = (1, (2, 3), (4, 5))
4.3.10 - Unpacking Tuples
Tuple unpacking allows assigning each value in the tuple to a variable:
a, b, c = my_tuple[:3]
4.3.11 - Immutable Nature of Tuples
Tuples are immutable, meaning their elements cannot be changed after creation. This makes them ideal for fixed data storage.
4.3.12 - Converting Lists to Tuples and Vice Versa
tuple(list)
: Converts a list to a tuple.list(tuple)
: Converts a tuple to a list.
Example:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
new_list = list(my_tuple)
4.3.13 - Named Tuples (collections.namedtuple)
Named tuples can be used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
pt = Point(1, 2)
print(pt.x, pt.y) # 1 2
4.3.14 - Summary Table of Tuple Methods and Techniques
Method/Technique | Description | Example |
---|---|---|
Creating Tuples | Define a tuple using parentheses. | my_tuple = (1, 2, 3) |
Accessing Elements | Access elements by their index. | element = my_tuple[0] |
Slicing Tuples | Get a subset of the tuple. | subset = my_tuple[:2] |
len(tuple) | Get the number of elements in the tuple. | length = len(my_tuple) |
Checking Item Existence | Check if an item exists in the tuple. | if 2 in my_tuple: ... |
Iterating Over Tuples | Iterate over tuple elements using a loop. | for x in my_tuple: print(x) |
Tuple Concatenation | Concatenate tuples using + . | concatenated = tuple1 + tuple2 |
Tuple Repetition | Repeat tuples using * . | repeated = tuple1 * 3 |
.index(element) | Get the index of the element. | my_tuple.index(3) |
.count(element) | Count occurrences of the element. | my_tuple.count(2) |
Nested Tuples | Tuples can contain other tuples. | nested = (1, (2, 3)) |
Unpacking Tuples | Assign each value in the tuple to a variable. | a, b, c = my_tuple |
Tuple Immutability | Tuples cannot be changed after creation. | |
Converting Lists to Tuples | Convert lists to tuples and vice versa. | tuple(my_list), list(my_tuple) |
collections.namedtuple | Create tuple-like objects with named fields. | Point = namedtuple('Point', ['x', 'y']) |