Python tuple

A Python tuple is similar to a Python list. The only difference is that a tuple is immutable in nature. Therefore the tuple elements can not be changed after creation. Similar to a Python list, a tuple can also contain different types of data types, such as strings, integers, objects, etc.


Creating a Python tuple

A tuple can be created by placing all the elements inside parentheses () and separating each element by a comma. However, parentheses are optional and a tuple can also be created by just separating each element by a comma without any parentheses. Although, it’s a good practice to use parentheses to create a tuple.

Note: Tuples are immutable(unchangeable) in nature.

# A program to create a tuple in Python
empty_tuple = ()  # It creates an empty tuple
print(empty_tuple) 

integers_tuple = (1, 2, 3) # A tuple of integers
print(integers_tuple)

tuple1 = (1, 'Programmers', 'Portal', 2, 3) # A tuple created using parentheses  
print(tuple1)

tuple2 = 1, 'Programmers', 'Portal', 2, 3   # A tuple created without parentheses
print(tuple2)

Output:

()
(1, 2, 3)
(1, 'Programmers', 'Portal', 2, 3)
(1, 'Programmers', 'Portal', 2, 3)

Creating a single element tuple

Creating a multiple-element tuple is cool. But What if we want to create a tuple which contains only one element. Now, you might be thinking what is different in this case. Let’s understand it.

# A Program to create a single element Python tuple

tuple1 = ('Hello',)  # It is necessary to place a comma after the single element
print(type(tuple1))  # Type of tuple1 ---> A tuple
print(tuple1)

tuple2 = ('Hello')   # If comma is not placed after single element it's not a Python tuple
print(type(tuple2))  # Type of tuple2 ---> A string
print(tuple2)        

Note: type() is a built-in method. It returns the type of the parameter passed to it.

Output:

<class 'tuple'>
('Hello',)
<class 'str'>
Hello

Note: If a tuple contains only one element, It’s necessary to place a comma after the element.


Accessing tuple items

Tuple items can be accessed using indexes. A Python tuple has indexing same as a Python list. The first item in a tuple has an index of 0, the second item as 1, the third item as 2, and so on up to the end of the tuple.

Note: The first item in a tuple has an index of 0.

# A program to demonstrate indexing in a Python tuple

sample_tuple = (1, 'Hello', 'welcome', 'to', 'Programmers', 'Portal', 5)

print(sample_tuple[0])  # Print first item
print(sample_tuple[1]) 
print(sample_tuple[4]) 
print(sample_tuple[5]) 
print(sample_tuple[6]) # Print last  item 

Output:

1
Hello
Programmers
Portal
5

Accessing tuple items using negative indexing

Tuple items can also be accessed using negative indexes. Negative indexes start from the end(rightmost element) of the tuple. The last item in a tuple has an index of -1, second last as -2, third last as -3, and so on towards the beginning of the tuple.

Note: In negative indexing, elements are traversed in reverse order.

# A program to demonstrate negative indexing in a Python tuple

my_tuple = (1, 'Programmers', 'Portal', 'Negative', 'Indexing', 5)
print(my_tuple[-1])  # Index -1 indicates the last element
print(my_tuple[-2])  # Index -2 indicates second the last element
print(my_tuple[-5])
print(my_tuple[-4])

Output:

5
Indexing
Programmers
Portal

Size(length) of a Python tuple

Python provides us an inbuilt method len() to get the size of a tuple.

Note: The len() method can also be used to get the size of a list, tuple, string, array etc. .

# A Python program to explain len() method

empty_tuple = ()
print(len(empty_tuple))

tuple1 = (1, 2, 3, 4, 5)
print(len(tuple1))

Output:

0
5

Slicing in a Python tuple

Slicing in a tuple is similar to a list. Python provides us a colon (:) operator which is used for slicing.

# A Python program to demonstrate slicing in a Python tuple

my_tuple = (1, 2, 3,'Programmers', 'Portal', 4, 5, 6, 7)

# Print a tuple starting from 3rd element up to 5th element(Excludes index 5)
print(my_tuple[2:5])

# Print a tuple starting from beginning up to 5th element (Excludes index 5) 
print(my_tuple[0:5])

# Print a tuple from beginning to 5th element
print(my_tuple[:5])

# Print a tuple starting from 2nd element up to last 
print(my_tuple[1:])

# Print the whole tuple
print(my_tuple[:])

# Using negative indexing in slicing
# Print a tuple staring from 5th last element up to last element(Exclude last element) 
print(my_tuple[-5:-1])

Output:

(3, 'Programmers', 'Portal')
(1, 2, 3, 'Programmers', 'Portal')
(1, 2, 3, 'Programmers', 'Portal')
(2, 3, 'Programmers', 'Portal', 4, 5, 6, 7)
(1, 2, 3, 'Programmers', 'Portal', 4, 5, 6, 7)
('Portal', 4, 5, 6)

Add, update and delete in a tuple

As we already know tuples are immutable in nature. Therefore, you can’t add or edit elements in the tuple. There is no such method as append() or extend() in tuples. You can also not remove existing elements from a tuple. So all these modifications are not permitted in tuples.

Let’s try updating a tuple.

# A program to demonstrate the immutable nature of tuples

my_tuple = (1, 2, 3, 4, 5)
my_tuple[0] = 10 # Try to replace 1 with 10
# Above line will throw an error

Output:

Traceback (most recent call last):
  File "jdoodle.py", line 4, in <module>
    my_tuple[0] = 10 # Try to replace 1 with 10
TypeError: 'tuple' object does not support item assignment

Note: Add, edit and delete operations are not allowed in tuples.


Basic tuple operations

1. Concatenation

It is possible to add two tuples and get a new one as a result of the two.

# A program to demonstrate tuple concatenation

tuple1 = ('Hello', 'Welcome', 'to')
tuple2 = ('Programmers', 'Portal')
tuple3 = tuple1 + tuple2
print('Tuple 1: ',tuple1)
print('Tuple 2: ',tuple2)
print('Tuple 3:', tuple3)

Output:

Tuple 1:  ('Hello', 'Welcome', 'to')
Tuple 2:  ('Programmers', 'Portal')
Tuple 3: ('Hello', 'Welcome', 'to', 'Programmers', 'Portal')

2. Repetition

Python provides us a repetition operator * , which can repeat a tuple as many time as we want.

# A program to demonstrate repetition in a tuple

tuple1 = (1, 2, 3, 4, 5)
tuple2 = tuple1*2   # It repeats tuple1 two times and assign it into tuple2
print('Tuple 1: ',tuple1)
print('Tuple 2: ',tuple2)


output:

Tuple 1:  (1, 2, 3, 4, 5)
Tuple 2:  (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

3. Membership

The membership operator (in) is used to check if an element exists in the tuple or not. If a given element is present in the tuple it returns a Boolean value true, otherwise, it returns false.

# A program to demonstrate membership operator (in) in a python tuple
my_tuple = (1, 2, 3, 'Programmers', 'Portal')
print(2 in my_tuple)
print(5 in my_tuple)
print('Programmers' in my_tuple)

Output:

True
False
True