THE WORLD'S LARGEST WEB DEVELOPER SITE

Python Tuples


Tuple

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

Example

Create a Tuple:

thistuple = ("apple", "banana", "cherry")
print(thistuple)
Run example »

Example

Return the item in position 1:

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Run example »

Example

You cannot change values in a tuple:

thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant" # test changeability
print(thistuple)
Run example »


The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple. The len() function returns the length of the tuple.

Example

Using the tuple() method to make a tuple:

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

Example

The len() method returns the number of items in a tuple:

thistuple = tuple(("apple", "banana", "cherry"))
print(len(thistuple))
Run example »

Note: You cannot remove items in a tuple.