Python 3 Tuples

Python 3 Tuples

Python Tuples are similar to lists, except that tuple elements cannot be modified.

Tuples use parentheses, while lists use square brackets.

Creating a tuple is simple: simply add elements within the parentheses and separate them with commas.

Example (Python 3.0+)

>>> tup1 = ('Google', 'Geekdoc', 1997, 2000)
>>> tup2 = (1, 2, 3, 4, 5 )
>>> tup3 = "a", "b", "c", "d" # Brackets are not required
>>> type(tup3)
<class 'tuple'>

Create an empty tuple

tup1 = ()

When a tuple contains only one element, you need to add a comma after the element; otherwise, the parentheses will be treated as operators:

Example (Python 3.0+)

>>>tup1 = (50)
>>> type(tup1) # Without the comma, the type is an integer
<class 'int'>

>>> tup1 = (50,)
>>> type(tup1) # With the comma, the type is a tuple
<class 'tuple'>

Tuples are similar to strings; subscript indexes start at 0 and can be truncated and combined.


Accessing Tuples

Tuples can use subscript indexing to access values in the tuple, as shown in the following example:

Example (Python 3.0+)

#!/usr/bin/python3

tup1 = ('Google', 'Geekdoc', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

The above example outputs:

tup1[0]: Google
tup2[1:5]: (2, 3, 4, 5)

Modifying Tuples

The values of elements in a tuple are not allowed to be modified, but tuples can be concatenated and combined, 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 tuple elements is illegal.
# tup1[0] = 100

# Create a new tuple
tup3 = tup1 + tup2
print (tup3)

The above example outputs:

(12, 34.56, 'abc', 'xyz')

Deleting a tuple

The element values in a tuple are not allowed to 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', 'Geekdoc', 1997, 2000)

print (tup)
del tup
print ("Deleted tuple tup : ")
print (tup)

After deleting the above example tuple, the output variable will contain an exception message, as shown below:

Deleted tuple tup :
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 they can be combined and copied, resulting in a new tuple.

Python expression Result Description
len((1, 2, 3)) 3 Count the number of elements
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenate
(‘Hi!’,) * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) Copy
3 in (1, 2, 3) True Is the element present?
for x in (1, 2, 3): print (x,) 1 2 3 Iteration

Tuple Indexing, Extraction

Because a tuple is also a sequence, we can access the element at a specific position in the tuple, or extract a range of elements from the index, as shown below:

Tuple:

L = ('Google', 'Taobao', 'Geekdoc')
Python expression Result Description
L[2] ‘Geekdoc’ Read the third element
L[-2] ‘Taobao’ Read in reverse, read the second to last element
L[1:] (‘Taobao’, ‘Geekdoc’) Truncate the elements, starting from the second one and all the elements after it.

The following example is shown:

>>> L = ('Google', 'Taobao', 'Geekdoc')
>>> L[2]
'Geekdoc'
>>> L[-2]
'Taobao'
>>> L[1:]
('Taobao', 'Geekdoc')

Tuple built-in functions

Python tuples contain the following built-in functions

Serial number Method and description
1 len(tuple)
Calculates the number of elements in a tuple.
>>> tuple1 = ('Google', 'Geekdoc', 'Taobao')
>>> len(tuple1)
3
>>> 
2 max(tuple)
Returns the maximum value of an element in a tuple.
>>> tuple2 = ('5', '4', '8')
>>> max(tuple2)
'8'
>>> 
3 min(tuple)
Returns the minimum value of an element in a tuple.
>>> tuple2 = ('5', '4', '8')
>>> min(tuple2)
'4'
>>> 
4 tuple(iterable)
Converts an iterable series to a tuple.
>>> list1= ['Google', 'Taobao', 'Geekdoc', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Geekdoc', 'Baidu')

About Tuples: Immutability

The immutability of tuples refers to the immutability of the memory content pointed to by the tuple.

>>> tup = ('g', 'e', 'e', 'k', 'd', 'o','c')<br>
>>> tup[0] = 'g'     # Modifying elements is not supported<br>
Traceback (most recent call last):<br>
  File "<stdin>", line 1, in <module><br>
TypeError: 'tuple' object does not support item assignment<br>
>>> id(tup)     # View memory address<br>
4440687904<br>
>>> tup = (1,2,3)<br>
>>> id(tup)<br>
4441088800    # The memory address is different<br>

As can be seen from the above example, the reassigned tuple tup, binds to a new object, does not modify the original object.

Leave a Reply

Your email address will not be published. Required fields are marked *