【Python】Collection - tuple

Posted by 西维蜀黍 on 2023-08-20, Last Modified on 2024-01-09

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 element
  • letters[-3] - accesses third last element

Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −

#!/usr/bin/python

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;

When the above code is executed, it produces the following result −

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

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]

Reference