Python ProgrammingPython Programming

Python Tuples

In this tutorial you will learn, how to create tuples and access the values from them.

Python tuple is a sequence, which can store heterogeneous data types such as integers, floats, strings, lists, and dictionaries. Tuples are written with round brackets and individual objects within the tuple are separated by a comma. The two biggest differences between a tuple and a list are that a tuple is immutable and allows you to embed one tuple inside another.


Create and Print

Tuples are a more general version of strings, because every item in the tuple is a separate object.

Example
Create and print different types of tuples:
tuple1 = ()   # An empty tuple.
tuple2 = (1, 2, 3)  # A tuple containing three integer objects.
 
# A tuple containing three string objects.
tuple3 = ("India", "Canada", "Japan")
 
# A tuple containing an integer, a string, and a boolean object.
tuple4 = (100, "Italy", False)
 
# A tuple containing another tuple.
tuple5 = (50, ("India", "Canada", "Japan"))
 
# The extra comma, tells the parentheses are used to hold a singleton tuple.
tuple6 = (25,)
 
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple5)
print(tuple6)
Output
()
(1, 2, 3)
('India', 'Canada', 'Japan')
(100, 'Italy', False)
(50, ('India', 'Canada', 'Japan'))
(25,)

Access Tuple Item

To access tuple item need to refer it by it's the index number, inside square brackets:

Example
Return the item at index position of 0 and 3:
tuple1 = ("India", "Canada", "Japan", "Italy")
 
print(tuple1[0])
print(tuple1[3])
Output
India
Italy

Iterate Over Tuple

You can iterate tuple items by using a for loop and in keyword.

Example
Iterate and print tuple item values:
testtuple = ("India", "Canada", "Japan", "Italy")
 
for item in testtuple:
    print(item)
 
Output
India
Canada
Japan
Italy

Check if Item Exists

You can verify if a specified item is exists in a tuple using in keyword:

Example
Check if "India" is exist in the tuple:
testtuple = ("India", "Canada", "Japan", "Italy")
 
if "India" in testtuple:
    print("Yes")
 
Output
Yes

Delete Tuple

You can use del keyword to delete a tuple.

Example
Tuple deleted completely
testtuple = ("India", "Canada", "Japan", "Italy")
del testtuple

Slicing of Tuple

In order to do slicing, use the square brackets with the index or indices.

Example
Slicing of tuple in different ways:
tuples = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
 
print(tuples[4:])  # From index 4 to last index
 
print(tuples[:4])  # From index 0 to 4 index
 
print(tuples[4:7])  # From index 4(included) up to index 7(excluded)
 
print(tuples[1::])  # Excluded First item
 
print(tuples[:-1])  # Excluded last item
 
print(tuples[:-2])  # Up to second last index(negative index)
 
print(tuples[::-1])  # From last to first in reverse order(negative step)
 
print(tuples[::-2])  # All odd numbers in reversed order
 
print(tuples[-2::-2])  # All even numbers in reversed order
 
print(tuples[::])  # All items
 
Output
(4, 5, 6, 7, 8, 9)
(0, 1, 2, 3)
(4, 5, 6)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
(0, 1, 2, 3, 4, 5, 6, 7, 8)
(0, 1, 2, 3, 4, 5, 6, 7)
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
(9, 7, 5, 3, 1)
(8, 6, 4, 2, 0)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Unpacking Tuples items

During unpacking of tuples items value assigned to variables.

Example
Tuple's items have been assigned to ind, can,... variables correspondingly.
countrylist = ("India", "Canada", "Japan", "Italy")
ind, can, jap, itl = countrylist
 
print(ind)
print(can)
Output
India
Canada

Convert List into Tuple

You can use tuple() method to convert a list into tuple:

Example
Type of "test" converted from List to Tuple:
test = ["India", "Canada", "Japan", "Italy"]
print(type(test))
 
test = tuple(test)
print(type(test))
Output



Sort Tuple Items

You can use sorted() method to sort items of tuple. But it should be of homogeneous data type:

Example
test1 = ("India", "Canada", "Japan", "Italy")
test2 = (27, 25, 5, 0)
test3 = (('India', 27),('Canada', 25),('Japan', 5), ('Italy', 0))
 
print(sorted(test1))
print(sorted(test2))
print(sorted(test3))
Output
['Canada', 'India', 'Italy', 'Japan']
[0, 5, 25, 27]
[('Canada', 25), ('India', 27), ('Italy', 0), ('Japan', 5)]

Concatenate Tuples

You can use + operator to concatenate two or more tuples.

Example
test1 = ("India", "Canada", "Japan", "Italy")
test2 = ("France", "Poland")
test3 = test1 + test2
 
print(test3)
Output
('India', 'Canada', 'Japan', 'Italy', 'France', 'Poland')

Convert Tuple into Dictionary

You can use dict() method to convert tuple into dictionary.

Example
Three different ways to convert tuple in dictionary:
test = (('India', 27), ('Canada', 25), ('Japan', 5), ('Italy', 0))
 
dict1 = dict(i for i in test)
dict2 = dict(map(reversed, test))
dict3 = dict(i[::1] for i in test)
 
print(dict1)
print(dict2)
print(dict3)
 
Output
{'India': 27, 'Japan': 5, 'Italy': 0, 'Canada': 25}
{0: 'Italy', 25: 'Canada', 27: 'India', 5: 'Japan'}
{'India': 27, 'Japan': 5, 'Italy': 0, 'Canada': 25}

Convert Tuple into String

You can use join() method to convert tuple into string.

Example
test = ("India", "Canada", "Japan", "Italy")
 
strtest = ','.join(test)
print(strtest)
Output
India,Canada,Japan,Italy

Tuple count() Method

You can use count() method to calculate the number of times a specified value appears in the tuple.

Example
test = ("Canada", "India", "Canada", "Japan", "Italy", "Canada")
 
num = test.count("Canada")
 
print(num)
 
Output
3

Tuple index() Method

You can use index() method to get first occurrence of the specified value in the tuple. Best practice is to use this method after determination of item exist in tuple, otherwise this will raise an exception.

Example
Search for the first occurrence of the value "Japan","Canada" or "Brazil", and return its index position:
test = ("Canada", "India", "Canada", "Japan", "Italy", "Canada")
 
idx = test.index("Japan")
 
print(idx)
 
idx = test.index("Canada")
 
print(idx)
 
if "Brazil" in test:
    idx = test.index("Brazil")
    print(idx)
Output
3
0