跳到主要内容

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.

tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male")

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Since tuples are indexed, they can have items with the same value:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")

len

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

type

mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
output
<class 'tuple'>

constructor

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

function

access

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
print(thistuple[-1])
print(thistuple[2:5])
print(thistuple[:4])
print(thistuple[2:])
print(thistuple[-4:-1])
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

update

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

unpack

When we create a tuple, we normally assign values to it. This is called "packing" a tuple:

But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking":

fruits = ("apple", "banana", "cherry") # packing

(green, yellow, red) = fruits # unpacking

print(green)
print(yellow)
print(red)

loop

thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

join

fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
output
("apple", "banana", "cherry", "apple","banana","cherry")
("a","b","c",1,2,3)
functiondescription
count()Returns the number of times a specified value occurs in a tuple
index()Searches the tuple for a specified value and returns the position of where it was found
Loading Comments...