Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

There are four collection data types in the Python programming language and Tuple is one of them, the other 3 are ListSet, and Dictionary, and each has different usage.

A tuple is a collection that is ordered and unchangeable and it allows duplicate members. You can remove and/or add items to a Tuple. And Tuple can hold different data types.

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

Creating a Tuple

A tuple is created by placing the elements inside parentheses, separated by commas. The parentheses are optional, however, it is a good practice to use them.

If you’re generating a tuple with a single element, make sure to add a comma after the element.

Tuple Examples:

# Different types of tuples

# Empty tuple
my_tuple = ()

# Tuple without parentheses
my_tuple = 1, 2, 3

# Tuple with single element 
# Tuple without parentheses
my_tuple = (1,)

# Tuple having integers
my_tuple = (1, 2, 3)

# tuple with mixed datatypes
my_tuple = (1, "Hello World", 4.4)

# tuple unpacking
a, b, c = my_tuple
print(a) # Output: 1 
print(b) # Output: Hello World
print(c) # Output: 4.4

# nested tuple
my_tuple = ("arjunphp", [1, 2, 3], (4, 5, 6))

# Code to create a tuple with repetition
my_tuple = ('arjunphp',)*3
# output: ('arjunphp', 'arjunphp', 'arjunphp')
# Try the above without a comma and check. You will get my_tuple as a string ‘arjunphparjunphparjunphp’.

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.

Python ExpressionResultsDescription
len((1, 2, 3))3Length
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)Concatenation
(‘Hi!’,) * 4(‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’)Repetition
3 in (1, 2, 3)TrueMembership
for x in (1, 2, 3): print x,1 2 3Iteration

Built-in Tuple Functions

Below are the Tuple functions:

len(tuple) – Gives the total length of the tuple.

tuple(seq) – Converts a list into tuple.

cmp(tuple1, tuple2) – Compares elements of both tuples.

max(tuple) – Returns item from the tuple with max value.

min(tuple) – Returns item from the tuple with min value.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.