Python Tuples
Python Tuples
Section titled “Python Tuples”A tuple is an ordered, immutable sequence of Python objects. ‘Immutable’ means that once a tuple is created, its elements cannot be changed, added, or removed. Tuples are similar to lists, but the key difference is their immutability.
Tuples are defined by enclosing comma-separated values within parentheses (). Parentheses are optional if the context is clear, but using them is standard practice.
# Creating tuplestuple1 = ('physics', 'chemistry', 1997, 2000)tuple2 = (1, 2, 3, 4, 5)tuple3 = "a", "b", "c", "d" # Parentheses optional here
empty_tuple = ()
# Tuple with a single element requires a trailing commasingle_element_tuple = (50,)not_a_tuple = (50) # This is just the integer 50
print(type(single_element_tuple)) # Output: <class 'tuple'>print(type(not_a_tuple)) # Output: <class 'int'>Like lists and strings, tuple elements are indexed starting from 0. You can access elements, slice them, concatenate tuples, and repeat them.
Accessing Values in Tuples
Section titled “Accessing Values in Tuples”Use square brackets [] with the index to access individual elements, or slicing [start:end:step] to get sub-tuples.
tup1 = ('physics', 'chemistry', 1997, 2000)tup2 = (1, 2, 3, 4, 5, 6, 7)
print(f"tup1[0]: {tup1[0]}") # Access first elementprint(f"tup2[1:5]: {tup2[1:5]}") # Slice from index 1 up to (not including) 5print(f"tup1[-1]: {tup1[-1]}") # Access last elementOutput:
tup1[0]: physicstup2[1:5]: (2, 3, 4, 5)tup1[-1]: 2000Updating Tuples (Immutability)
Section titled “Updating Tuples (Immutability)”Tuples are immutable. You cannot change an element within a tuple after it’s created.
tup1 = (12, 34.56)
# The following action is INVALID and will raise a TypeError:# tup1[0] = 100# TypeError: 'tuple' object does not support item assignmentHowever, you can create new tuples by combining existing tuples or parts of them.
tup1 = (12, 34.56)tup2 = ('abc', 'xyz')
# Create a new tuple by concatenating tup1 and tup2tup3 = tup1 + tup2print(f"New tuple tup3: {tup3}")Output:
New tuple tup3: (12, 34.56, 'abc', 'xyz')If a tuple contains a mutable object (like a list), the contents of that mutable object can be changed, but the object itself remains at the same position within the tuple.
tuple_with_list = (1, 2, ['a', 'b'])print(f"Original: {tuple_with_list}")
# Modify the list inside the tuple (this is allowed)tuple_with_list[2].append('c')print(f"Modified: {tuple_with_list}")
# Attempting to replace the list object itself fails# tuple_with_list[2] = ['x', 'y'] # TypeError!Delete Tuple Elements
Section titled “Delete Tuple Elements”Because tuples are immutable, you cannot remove individual elements from a tuple.
You can, however, delete an entire tuple object using the del statement.
tup = ('physics', 'chemistry', 1997, 2000)
print(f"Original tuple: {tup}")
# Delete the entire tuple objectdel tup
# Attempting to access 'tup' now will raise a NameError# print(tup)# NameError: name 'tup' is not definedprint("Tuple 'tup' has been deleted.")Basic Tuple Operations
Section titled “Basic Tuple Operations”Tuples support standard sequence operations like concatenation (+) and repetition (*), which result in new tuples.
| Python Expression | Result | Description |
|---|---|---|
len((1, 2, 3)) | 3 | Length |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | Concatenation |
('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | Repetition |
3 in (1, 2, 3) | True | Membership checking |
for x in (1, 2, 3): print(x, end=' ') | 1 2 3 | Iteration |
Indexing and Slicing
Section titled “Indexing and Slicing”Indexing and slicing work just like with lists and strings.
T = ('spam', 'Spam', 'SPAM!', 'eggs')| Python Expression | Result | Description |
|---|---|---|
T[0] | 'spam' | First element (index 0) |
T[-1] | 'eggs' | Last element |
T[1:3] | ('Spam', 'SPAM!') | Slice from index 1 up to (not including) 3 |
T[::2] | ('spam', 'SPAM!') | Every second element |
Tuple Unpacking
Section titled “Tuple Unpacking”A very common and powerful feature is tuple unpacking, where you assign the elements of a tuple to individual variables. The number of variables must match the number of elements in the tuple.
point = (10, 20, 30)x, y, z = point # Unpacking
print(f"x = {x}, y = {y}, z = {z}")
# Can be used for easy swappinga = 5b = 10a, b = b, a # Swap values using tuple packing/unpackingprint(f"Swapped: a = {a}, b = {b}")
# Extended unpacking (Python 3)numbers = (1, 2, 3, 4, 5)first, second, *rest = numbersprint(f"first: {first}, second: {second}, rest: {rest}")
first, *middle, last = numbersprint(f"first: {first}, middle: {middle}, last: {last}")Output:
x = 10, y = 20, z = 30Swapped: a = 10, b = 5first: 1, second: 2, rest: [3, 4, 5]first: 1, middle: [2, 3, 4], last: 5Built-in Tuple Functions
Section titled “Built-in Tuple Functions”Python includes functions that can operate on tuples:
| Function | Description |
|---|---|
len(tuple) | Gives the total number of items in the tuple. |
max(tuple) | Returns the item from the tuple with the maximum value (items must be comparable). |
min(tuple) | Returns the item from the tuple with the minimum value (items must be comparable). |
sum(tuple) | Returns the sum of all items in the tuple (items must be numeric). |
tuple(iterable) | Converts an iterable (like a list, string, or range) into a tuple. |
sorted(tuple) | Returns a new list containing all items from the tuple in ascending order. |
Note: The cmp(tuple1, tuple2) function from Python 2 is removed in Python 3. Use standard comparison operators (<, >, ==, etc.) which work lexicographically on tuples.
Why Use Tuples?
Section titled “Why Use Tuples?”Despite their similarity to lists, tuples are useful in several scenarios: