Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
初始化
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# or
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
One item tuple, remember the comma:
>>> thistuple = ("apple",)
>>> type(thistuple)
<class 'tuple'>
#NOT a tuple
thistuple = ("apple")
type(thistuple)
<class 'str'>
基本操作
Indexing
We can use the index operator []
to access an item in a tuple, where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range( 6,7,… in this example) will raise an IndexError
.
The index must be an integer, so we cannot use float or other types. This will result in TypeError
.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
# accessing tuple elements using indexing
letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")
print(letters[0]) # prints "p"
print(letters[5]) # prints "a"
Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. For example,
# accessing tuple elements using negative indexing
letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(letters[-1]) # prints 'z'
print(letters[-3]) # prints 'm'
In the above example,
letters[-1]
- accesses last elementletters[-3]
- accesses third last element
Misc
# Concatenation
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
# Repetition
>>> ('Hi!',) * 4
('Hi!', 'Hi!', 'Hi!', 'Hi!')
# sort
>>> numbers = (14, 3, 1, 4, 2, 9, 8, 10, 13, 12)
>>> sorted(numbers)
[1, 2, 3, 4, 8, 9, 10, 12, 13, 14]
>>> T = (1, 2, 3, 4) # Indexing, slicing
>>> T[0], T[1:3]
(1, (2, 3))
Reference
- Learning Python
- Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming