Tuple is another data structure similar to list, supported by Python. It is very similar to lists but different in mainly two points.
- First, a Tuple is sequence of immutable objects. This means that while you can change the value of one or more elements in a list, But you can’t change the value of elements in a tuple.
- Second, tuples use parenthesis to define its elements where as lists use square brackets.
How to create Tuple in Python?
Looks, interesting data structure. Creation of tuple is also very simple and almost similar to creation of list. Generally you need to just put the different comma-separated values within a parenthesis as shown below.
Tup = (value1, value2, value3, ...) # value can be integer, floating number, character or string.
Tup = (1, 2, 3, 4, 5) # create a tuple of integers print(Tup) Tup = ('a', 'b', 'c', 'd', 'e') # Create a tuple of Character print(Tup) Tup = ("welcome", "To", "Freshlybuilt.com") # Create a tuple of string print(Tup) Tup = (1.2, 2.4, 5.6, 6.5) # Create a tuple of Floating Number print(Tup) Tup = (1, "abc", 2.1, "a") # Create a tuple of mixed values print(Tup)
(1,2,3,4,5) ('a', 'b', 'c', 'd', 'e') ("welcome", "To", "Freshlybuilt.com") (1.2, 2.4, 5.6, 6.5) (1, "abc", 2.1, "a")
Key Points to remember during creation of tuple
- Any set of multiple, comma-separated value written without an identifying symbol like brackets  and parentheses(), etc are treated as tuple by default.
- If you want to create a tuple with a single element, then you must add a comma after the element. In the absence of a comma, Python treats the elements as an ordinary data type.
# Tuple with Parentheses print(1, 2 , "a") # Default Tuple without parentheses x, y = 1, 2 print(x, y) # Comma after first element Tup = (1, ) print(type(Tup)) # Missing Comma Tup = (1) print(type(Tup))
1 2 a 1 2 <type 'tuple'> <type 'int'>
Accessing Values of tuple in Python
Like Strings and Lists, indices in a tuple also start at 0. Programmer can even perform operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple, slice operation is used along with the index or indices to obtain value stored at that index.
Tup = (1, 2, 3, 4, 5) print(" Tup[1:3] = ", Tup[1:3]) print(" Tup[ : ] = ", Tup[ : ])# print whole tuple
Tup[1:3] = (2, 3) Tup[ : ] = (1, 2, 3, 4, 5)
Update operation on Tuple
Tuple is Immutable in nature , so the value(s) in the tuple cannot be changed. Programmer can only extract values from a tuple to form another tuple.
Deleting Elements in Tuple
Since tuple is an Immutable in nature, you cannot delete value(s) from it. Of course, you can create a new tuple that has all elements in your tuple except the ones you don’t want (those you wanted to be deleted).
However, you can delete the entire tuple by using the del statement. Deletion of single element or some element is not possible in tuple in Python.
Tup = (1, 2, 3) del Tup print(Tup)
NameError: name "Tup" is not defined
Program to illustrate that tuples are immutable
Tup = (1, 2, 3) del Tup print(Tup)
TypeError: 'tuple' object doesn't support item deletion
Assignment of Tuple
It is very important feature in python. It allows a tuple of variables on the left side of the assignment operator to be assigned values from a tuple given on right side of the assignment operator. Each value is assigned to respective variable.
Things become interesting when, an expression is specified on the right side of the assignment operator, first that expression is evaluated and then assignment is done. This feature makes tuple assignment quite versatile.
# an unnamed tuple of values assigned to values of another unnamed tuple (value1, value2, value3) = (1, 2, 3) print(value1, value2, value3) # expressions are evaluated before assignment (value1, value2, value3) = (1+2, 3/2, 7%3) print(value1, value2, value3)
1 2 3 3 1 4
Note: While assignment of values to a tuple, programmer must ensure that number of values on both the sides of the assignment operator are same otherwise, an error will be generated.
When tuple is lies inside another tuple, it is known as nested tuple.
Tup = (("x",1), ("y",2)) # nested tuple for i in Tup: print(i)
("x", 1) ("y", 2)
index() and count() in Tuple
Index of an element in the tuple can be obtained by using the index() method. If the element is not present inside the tuple, then error is generated.
Tup = (1, 3, 5, 4) print(Tup.index(5)) print(Tup.count(3))
Key point to remember
- Tuples can be converted into lists, and vice versa the built-in tuple ( ) function that takes a list and returns a tuple with a same elements .similarly, the list ( ) function takes a tuple and returns a list .
- You cannot divide or subtract tuple.if you try to do so you will get a typerror with ”unsupported oper and type”.
- Since tuple are immutable ,they do not support methods like sort ( ) and reverse ( ),as these methods modify existing lists .However, Python has a built-in function sorted() which takes any sequence as a parameter and returns a new list with the same elements but in different order. For example,
Tup = (1, 5, 3, 2) print(sorted(Tup))
[1, 2, 3, 5]
Advantages of Tuple over list
- Tuples are used to store values of different data types. List can however store data of similar data type.
- Since Tuples are immutable, iterating through tuple is faster than iterating over a list. This means that tuple perform better than a list.
- Tuples can be used as key for a dictionary, but list cannot be used as keys.
- Tuples are best suited for storing data that is write-protected (Programmer can read the data, but cannot write to it ).
- Tuples can be used in place of lists where the number of values is known and small.
- If you are passing a tuple as an argument to a function, then the potential for unexpected behaviour due to aliasing gets reduced.
- Multiple value from a function can be returned using a tuple.
- Tuples are used to format strings.