Python Tuples
Tuples in Python are similar to lists, with the key difference that the elements in a tuple cannot be modified.
Tuples use parentheses ( )
while lists use square brackets [ ]
.
Creating a tuple is simple—just place the elements inside parentheses and separate them with commas.
Example (Python 3.0+)
>>> tup1 = ('Google', 'Runoob', 1997, 2000) >>> tup2 = (1, 2, 3, 4, 5) >>> tup3 = "a", "b", "c", "d" # Parentheses are optional >>> type(tup3) <class 'tuple'>
Creating an Empty Tuple
tup1 = ()
When a tuple contains only one element, a comma must be added after the element; otherwise, the parentheses will be interpreted as a mathematical expression:
Example (Python 3.0+)
>>> tup1 = (50) >>> type(tup1) # Without a comma, the type is integer <class 'int'> >>> tup1 = (50,) >>> type(tup1) # With a comma, the type is tuple <class 'tuple'>
Tuples, like strings, are indexed starting from 0 and can be sliced and concatenated.
Accessing Tuple Elements
Tuples can be accessed using index numbers. Here’s an example:
Example (Python 3.0+)
#!/usr/bin/python3 tup1 = ('Google', 'Runoob', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7) print("tup1[0]: ", tup1[0]) print("tup2[1:5]: ", tup2[1:5])
Output:
tup1[0]: Google tup2[1:5]: (2, 3, 4, 5)
Modifying Tuples
Tuple elements cannot be modified, but you can concatenate tuples to create a new tuple:
Example (Python 3.0+)
#!/usr/bin/python3 tup1 = (12, 34.56) tup2 = ('abc', 'xyz') # The following operation is illegal: # tup1[0] = 100 # Create a new tuple tup3 = tup1 + tup2 print(tup3)
Output:
(12, 34.56, 'abc', 'xyz')
Deleting Tuples
While individual elements of a tuple cannot be deleted, you can delete the entire tuple using the del
statement:
Example (Python 3.0+)
#!/usr/bin/python3 tup = ('Google', 'Runoob', 1997, 2000) print(tup) del tup print("Tuple after deletion:") print(tup)
After deleting the tuple, trying to access it will raise an exception. The output would be as follows:
Tuple after deletion: Traceback (most recent call last): File "test.py", line 8, in <module> print(tup) NameError: name 'tup' is not defined
Tuple Operators
Like strings, tuples can be operated on using the +
, +=
, and *
operators. This means tuples can be concatenated and repeated, resulting in a new tuple.
Python Expressions
Python Expression | Result | Description |
---|---|---|
len((1, 2, 3)) | 3 | Counts the number of elements |
a = (1, 2, 3) | ||
b = (4, 5, 6) | ||
c = a + b | (1, 2, 3, 4, 5, 6) | Concatenation of two tuples |
a += b | (1, 2, 3, 4, 5, 6) | Concatenates and assigns to a |
('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | Repeats the tuple |
3 in (1, 2, 3) | True | Checks if an element exists |
for x in (1, 2, 3): print(x, end=" ") | 1 2 3 | Iterates through the tuple |
Tuple Indexing and Slicing
Since tuples are also sequences, you can access specific elements by index and slice segments of the tuple.
Consider the following tuple:
tup = ('Google', 'Runoob', 'Taobao', 'Wiki', 'Weibo', 'Weixin')
Python Expression | Result | Description |
---|---|---|
tup[1] | 'Runoob' | Reads the second element |
tup[-2] | 'Weibo' | Reads the second-to-last element (from the end) |
tup[1:] | ('Runoob', 'Taobao', 'Wiki', 'Weibo', 'Weixin') | Slices from the second element onwards |
tup[1:4] | ('Runoob', 'Taobao', 'Wiki') | Slices from the second element to the fourth |
Example:
>>> tup = ('Google', 'Runoob', 'Taobao', 'Wiki', 'Weibo', 'Weixin') >>> tup[1] 'Runoob' >>> tup[-2] 'Weibo' >>> tup[1:] ('Runoob', 'Taobao', 'Wiki', 'Weibo', 'Weixin') >>> tup[1:4] ('Runoob', 'Taobao', 'Wiki')
Tuple Built-in Functions
Python provides several built-in functions to work with tuples.
No. | Function & Description | Example |
---|---|---|
1 | len(tuple) - Returns the number of elements in a tuple. | python >>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 |
2 | max(tuple) - Returns the largest element in the tuple. | python >>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' |
3 | min(tuple) - Returns the smallest element in the tuple. | python >>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' |
4 | tuple(iterable) - Converts an iterable to a tuple. | python >>> list1 = ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1 = tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu') |
Immutability of Tuples
The immutability of tuples refers to the fact that the contents of a tuple's memory cannot be changed.
Example:
>>> tup = ('r', 'u', 'n', 'o', 'o', 'b') >>> tup[0] = 'g' # Modifying tuple elements is not supported Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
You can check the memory address of the tuple using the id()
function:
>>> id(tup) # Check the memory address 4440687904 >>> tup = (1, 2, 3) >>> id(tup) 4441088800 # Memory address changes after reassignment
As seen from the example, reassigning tup
binds it to a new object, rather than modifying the original one.