Python Tuple

Tuple is a collection data type in python that items are ordered, immutable and indexed by default.

When we need to store many items that are not going to be changed we can use Tuple data type instead of list.

Note: Here, immutable means, you can't change existing tuple items, add a new item or remove a tuple items once created. So, be careful when you are going to use Tuple in your production grade application and please check out your requirements.

# Syntax:


# items that are comma separated
tuple_name = a, b, c 
# using parentheses ()
tuple_name = (a, b, c)
# if your Tuple contains one item, extra comma is required
tuple_name = (a,)
# using tuple constructor - tuple()
tuple_name = tuple((a, b, c))

Note: It is actually the comma which makes the tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a, b, c) is a function call with three arguments, while f((a, b, c)) is a function call with a 3-tuple as the sole argument.

# Creating a tuple

Let's create a simple tuple and print it's value to the console


languages = ("Java", "Python", "C++") 
print(languages)

Output you will get in the console after running the above program.


('Java', 'Python', 'C++')

# Using type() function

The built in type() function returns the type of the variable, we create in python. As tuples are type of objects with the data type tuple, so the type() function returns


# creating a simple tuple
languages = ("Java", "Python", "C++") 
# using type() function
print(type(languages))

# Output: < class 'tuple'>

# Accessing the tuple items

As tuple is index based, thus we can access the elements or items of tuple data type using the index number. Like tuple [0] returns the first item, tuple[1] second item or tuple[lent(tuple) - 1] last item.

Look at the example below:


languages = ("Java", "Python", "C++", "Rust") 
print(languages[0]) # returns Java
print(languages[1]) # returns Python
print(languages[len(languages) - 1]) # returns Rust 

# We can also use the negative indexing to print the last element of the tuple
print(languages [-1]) # also returns Rust

Run the above python file again, you get the following output in the console:


Java
Python
Rust
Rus

# Find out the length of the tuple using the built in len() function

We can use Python built in len() function to get the length of the tuple easily. Note: Length is one more than the total index number as index number starts from 0 to (length - 1). numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(len(numbers)) # Output: 10 # As there are total 10 elements exists

# Converting a tuple to a list.

We can simply convert a tuple type to a list using the list() constructor (it's called type conversion). For example,


languages = ("Java", "Python", "C++") 
list = list(languages) # converts to a list
print(list)

# Output: ['Java', 'Python', 'C++']

# Tuple allow duplicate elements


languages = ("Java", "Python", "C++", "Java")
print (languages)

# Output: ('Java', 'Python', 'C++', 'Java')

# Change Tuples item

We know that tuples are immutable (not changeable), thus we can't change any tuple item once created, even we can't add new item in the existing tuple once created. (It provides more restrictions than python list or set data type). For example,


languages = ("Java", "Python", "C++") 

# try to change the first item 
languages [0] = "Rust"
print(languages)

# Output: TypeError: 'tuple' object does not support item assignment

# Iterate tuple items using for loop


languages = ("Java", "Python", "C++")
for lang in languages:
  print(lang)

Then the output should be:


Java
Python
C++

The above code can also be written using python built in range() function


languages = ("Java", "Python", "C++")
for lang in range(len(languages)): # it now stores the index number
  print(languages [lang])

The same output:


Java
Python
C++

# Delete a tuple

Using “del tuple_name” will delete the tuple type completely. Such as,


languages = ("Java", "Python", "C++")
del languages # this tuple has been deleted

print(languages) # raised NameError

# Output: NameError: name 'languages' is not defined

# Tuple methods

Python provides two built in methods to work with tuple as well as other optional methods.

Index(): returns the position or index number of the element in a certain tuple.
count(): calculate and return the number of a item in a tuple (means, how many times an element or item is occured)

Let's see a simple example to understand better the use of index() and count() method.


# index() method
languages = ("Java", "Python", "C++", "Java", "Java")
print(languages.index("C++")) # returns the index number of C++ item

print(languages.count("Java")) # returns the number, how many times Java present in this tuple


# Output: 
2 # index number (C++ position)
3 # how many times "Java" occurs (There are 3 times "Java" element is occured)