Python3 Tuples
Tuples in Python are similar to lists, with the difference being that the elements of a tuple cannot be modified.
Tuples use parentheses ( )
, while lists use square brackets [ ]
.
Creating a tuple is straightforward; simply add elements within parentheses and separate them with commas.
Example (Python 3.0+)
>>> tup1 = ('Google', 'tutorialpro', 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 treated as an operator:
Example (Python 3.0+)
>>> tup1 = (50)
>>> type(tup1) # Without a comma, the type is int
<class 'int'>
>>> tup1 = (50,)
>>> type(tup1) # With a comma, the type is tuple
<class 'tuple'>
Tuples are similar to strings; index starts from 0 and they can be sliced and concatenated.
Accessing Tuples
You can access the values in a tuple using index numbers, as shown in the following example:
Example (Python 3.0+)
#!/usr/bin/python3
tup1 = ('Google', 'tutorialpro', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])
Output of the above example:
tup1[0]: Google
tup2[1:5]: (2, 3, 4, 5)
Modifying Tuples
Elements in a tuple cannot be modified, but we can concatenate tuples to form new ones, as shown in the following example:
Example (Python 3.0+)
#!/usr/bin/python3
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# The following operation to modify a tuple element is illegal.
# tup1[0] = 100
# Create a new tuple
tup3 = tup1 + tup2
print(tup3)
Output of the above example:
(12, 34.56, 'abc', 'xyz')
Deleting a Tuple
Elements in a tuple cannot be deleted, but we can use the del
statement to delete the entire tuple, as shown in the following example:
Example (Python 3.0+)
#!/usr/bin/python3
tup = ('Google', 'tutorialpro', 1997, 2000)
print(tup)
del tup
print("Tuple 'tup' after deletion: ")
print(tup)
Output after deleting the tuple will result in an exception, as shown below:
Tuple 'tup' 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 support operations such as +
, +=
, and *
. This means they can be concatenated and replicated, resulting in a new tuple.
Python Expression | Result | Description |
---|---|---|
len((1, 2, 3)) | 3 | Counts the number of elements |
>>> a = (1, 2, 3)<br>>>> b = (4, 5, 6)<br>>>> c = a+b<br>>>> c<br>(1, 2, 3, 4, 5, 6) | (1, 2, 3, 4, 5, 6) | Concatenation, c is a new tuple containing all elements from a and b. |
>>> a = (1, 2, 3)<br>>>> b = (4, 5, 6)<br>>>> a += b<br>>>> a<br>(1, 2, 3, 4, 5, 6) | (1, 2, 3, 4, 5, 6) | Concatenation, a becomes a new tuple containing all elements from a and b. |
('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | Replication |
3 in (1, 2, 3) | True | Checks if an element exists |
for x in (1, 2, 3): <br> print(x, end=" ") | 1 2 3 | Iteration |
Tuple Indexing and Slicing
Tuples support indexing and slicing similar to strings. Since a tuple is also a sequence, we can access elements at specified positions in the tuple, or slice a segment of elements by index, as shown below:
Tuple:
tup = ('Google', 'tutorialpro', 'Taobao', 'Wiki', 'Weibo', 'Weixin')
Python Expression | Result | Description |
---|---|---|
tup[1] | 'tutorialpro' | Reads the second element |
tup[-2] | 'Weibo' | Reads in reverse, the second-to-last element |
tup[1:] | ('tutorialpro', 'Taobao', 'Wiki', 'Weibo', 'Weixin') | Slices elements, all elements from the second onwards |
tup[1:4] | ('tutorialpro', 'Taobao', 'Wiki') | Slices elements, from the second to the fourth element (index 3) |
Example usage:
Example
>>> tup = ('Google', 'tutorialpro', 'Taobao', 'Wiki', 'Weibo', 'Weixin')
>>> tup[1]
'tutorialpro'
>>> tup[-2]
'Weibo'
>>> tup[1:]
('tutorialpro', 'Taobao', 'Wiki', 'Weibo', 'Weixin')
>>> tup[1:4]
('tutorialpro', 'Taobao', 'Wiki')
>>>
Built-in Functions for Tuples
Python tuples include the following built-in functions:
Number | Method and Description | Example |
---|---|---|
1 | len(tuple) <br>Calculates the number of elements in the tuple. | >>> tuple1 = ('Google', 'tutorialpro', 'Taobao')<br>>>> len(tuple1)<br>3<br>>>> |
2 | max(tuple) <br>Returns the maximum value in the tuple. | >>> tuple2 = ('5', '4', '8')<br>>>> max(tuple2)<br>'8'<br>>>> |
3 | min(tuple) <br>Returns the minimum value in the tuple. | >>> tuple2 = ('5', '4', '8')<br>>>> min(tuple2)<br>'4'<br>>>> |
4 | tuple(iterable) <br>Converts an iterable series into a tuple. | >>> list1= ['Google', 'Taobao', 'tutorialpro', 'Baidu']<br>>>> tuple1=tuple(list1)<br>>>> tuple1<br>('Google', 'Taobao', 'tutorialpro', 'Baidu') |
On the Immutability of Tuples
The immutability of a tuple refers to the fact that the contents of the memory it points to cannot be changed.
>>> tup = ('r', 'u', 'n', 'o', 'o', 'b')
>>> tup[0] = 'g' # Modifying elements is not supported
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> id(tup) # Check memory address
4440687904
>>> tup = (1,2,3)
>>> id(tup)
4441088800 # The memory address has changed
From the above examples, it can be seen that the reassigned tuple tup
is bound to a new object, not modifying the original object.