Python tuples

Like lists, tuples are also used to store multiple values in a single variable. It is a collection that is ordered and unchangeable. Unlike lists, Tuples are written with round brackets.

Example

sample_tuple = ("east", "west", "north", "south")
print(sample_tuple)

Output:

(“east”, “west”, “north”, “south”)

Tuples are ordered

Tuples are ordered, this means that the items have a defined order, and that order will not change.

Tuples are Unchangeable

This means that we cannot add new items, change or remove items once the tuple has been created.

How to find the type of a tuple?

The type function can be used to check the data type of a tuple.

Example

mytuple = ("orange", "apple", "mango", "cherry")
print(type(mytuple))

Output:

<class ‘tuple’>

Duplicates are allowed in tuples

Tuples are indexed, they can have same items at different indexes.

Example

fruits = ("mango", "orange", "guava", "cherry", "orange")
print(fruits[1])
print(fruits[4])

Output:

orange
orange

How to find the length of a tuple?

To find out the length of a tuple, we use the len() function.

Example

fruits = ("mango", "orange", "guava", "cherry")
print(len(fruits))

How to create Tuple With One Item?

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.

Example

fruit = ("mango",)
print(type(fruit))

#Incorrect approach

fruit = ("mango")
print(type(fruit))

Data types inside a tuple

A tuple can have any type of values.

Example

citiesTuple = ("Delhi", "London", "Paris", "Italy")
numTuple = (1,2,4,5)
anotherTuple = (True, False)

Not only this, but a tuple can contain mixture of different types of values.

sample = ("Delhi", 7, True)

Type of a tuple

Tuples are objects with the data type tuple. You check the data type of a tuple by using the python inbuilt function type().

Example

sample = ("Delhi", "London", "Paris", "Italy")
print(type(sample))

Output:

<class ‘tuple’>

Converting a list to a tuple

You can convert a list to a tuple by using the tuple() function.

Example

countryList = ["Delhi", "London", "Paris", "Italy"]
countryTuple = tuple(countryList)

print(countryTuple)
print(type(countryTuple))

Output:

(“Delhi”, “London”, “Paris”, “Italy”)
<class ‘tuple’>

The tuple function is also considered as the tuple constructor, which can also be used to create a tuple

Example

mytuple = tuple((("Delhi", "London", "Paris", "Italy")))
print(mytuple)

Output:

(“Delhi”, “London”, “Paris”, “Italy”)