Python Tuples

Tuple

  • A tuple is a collection which is ordered and unchangeable.
  • In Python tuples are written with round brackets.
  • A tuple is a Immutable python objects.
  • It is similar to lists.
  • Main difference between lists and tuples is that tuples cannot be changed which means the values in the tuple cannot be changed where as in lists the value in the list can be altered.

You can learn more about lists from below link,

A tuple is represented by using ‘ ()’ round brackets or parenthesis. For example,

>>>tuple = () #Empty tuple
>>>print(tuple)
()

Above declared tuple is an empty tuple.

A tuple can store all the data types in it. For example,

#t1 is a tuple that holds characters, integers, float values and strings
>>>t1 = ('a','b',1,2,3.14,'string')
>>>print(t1)
('a', 'b', 1, 2, 3.14, 'string')

Another type of representation of tuple is

# We can represent a tuple using double codes
>>>t2 = "a","b","c","d"
>>>print(t2)
('a', 'b', 'c', 'd')

If you want to check whether the above declared t2 is a tuple or not. We can use type() function to know the class of t2.

>>>print(type(t2))
<class 'tuple'>

Therefore, the above declared t2 is a tuple.

We can also store a list in a tuple. For example,

>>>t3 = (1,2,3,['a','b','c'])
>>>print(t3)
(1, 2, 3, ['a', 'b', 'c'])

t3 is a tuple with a list in it. [‘a’, ‘b’ , ‘c’] is a list in t3.

To store only a single value in the tuple there must be a comma after the value.

#For a single valued tuple there is a need to put coma at the end
>>>t = (5,)
>>>type(t)
Tuple

Otherwise it will read it as a number. For example

>>>t = (5)
>>>type(t)
int

In the above code, t is declared same as tuple with round brackets but when we try to check the type of ‘t’ it gives int as there is no coma at the end of the value. Therefore, there is need to put coma at the end of a single value in the tuple.

Accessing values in tuples:

You can access tuple values by referring to the index number, inside square brackets:

>>>t1 = ('a','b',1,2,3.14,'string')
#The value at 0th index will be printed
>>>t1[0]
'a'

The index starts from 0. So, the first value in the tuple will be returned when we use t1[0]. Below is the way how the values are stored in python.

 Positive index---->   0  1   2  3   4     5
a b 1 2 3.14 string
Negative Index---> -6 -5 -4 -3 -2 -1

Python supports negative indexing too as already mentioned in lists. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item and so on…

>>>t1 = ('a','b',1,2,3.14,'string')
>>>t1[-1]
'string'

Slice Operator:

  • You can specify a range of indexes by specifying where to start and where to end the range.
  • When specifying a range, the return value will be a new tuple with the specified items.
>>>t1 = ('a','b',1,2,3.14,'string')
>>>t1[1:3]
('b', 1)

The range starts from 1(included) and 3(excluded). So, the values at the index 1 and 2 are given as output. The first value index starts from 0.

Range of values using negative indexes.

>>>t1 = ('a','b',1,2,3.14,'string')
>>>t1[-3:-1]
(2, 3.14)

The same applies here, -3 (include) and -1(excluded). Therefore, the values at the index -3 and -2 are given as output.

Can the values in Tuple be changed?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

>>>t1 = (‘a’,’b’,1,2,3.14,’string’)
>>>t1[0] = ‘c’

Here I am trying to change the value at index 0 from ‘a’ to ‘c’. When I try to execute it throws an error as shown below.

TypeError   Traceback (most recent call last)
<ipython-input-11-dbb1e7bc3add> in <module>
1 t1 = ('a','b',1,2,3.14,'string')
----> 2 t1[0] = 'c'

TypeError: 'tuple' object does not support item assignment

Therefore, the values in the tuple cannot be changed directly. But there is another way to change the values in the tuple. we can convert the tuple to a list using list() function and change the values in the list as lists are mutable. Then again convert the list to a tuple using tuple() function.

#t1 is a tuple
>>>t1 = (‘a’,’b’,1,2,3.14,’string’)
# converting the tuple to list
>>>lst = list(t1)
>>>lst[0] = 'c' #The value at index 0 is changed
#Displaying the values in the list
>>>lst
['c', 'b', 1, 2, 3.14, 'string']
#converting the list to tuple
>>>t1 = tuple(lst)
>>>t1
('c', 'b', 1, 2, 3.14, 'string')

Here, we are trying to change the first value in the tuple from ‘a’ to ‘c’. But we have already seen that we cannot change the values in the tuple directly. So, we have converted the tuple ‘t1’ to list ‘lst’ . Then change the value in the list from ‘a’ to ’c’. Then again convert the list to tuple ‘t1’ . Thus, the value at the index 0 is change in the tuple ‘t1’.

You can see more about lists in Python Lists.

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

>>>for val in t1:
... print(val,end=" ")
c b 1 2 3.14 string

To check if a value is present in the tuple, we can use ‘in’ keyword that is supported in python.

>>>if 'c' in t1:
... print("yes")
...else:
print("No")
yes

Remove Items

Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:

>>>del t1

Tuple Length

To determine how many items a tuple has, use the len() method:

>>>t1 = (‘a’,’b’,1,2,3.14,’string’)
>>>len(t1) #Number of values in the tuple
6

Operators in Tuple:

The operators that are supported in tuples are

  • + concatenation Operator
  • * Replication Operator

Concatenation Operator: Operator is used to Join two tuples.

Syntax: (tuple) + (tuple)

t1 = ('a','b',1,2,3.14,'string')
t2 = ('x','y','z')
print(t1+t2) #Concatenation Operator

The output of the above code will be:

('a', 'b', 1, 2, 3.14, 'string', 'x', 'y', 'z')

Thus, the tuples t1 and t2 are combined.

Replication Operator: It is used to replicate means repeat the tuple for any no. of times specified.

Syntax: (tuple) * (integer)

print(t1*2) # Replication Operator

The output will be:

('a', 'b', 1, 2, 3.14, 'string', 'a', 'b', 1, 2, 3.14, 'string')

The tuple ‘t1’ repeated for two times.

Tuple Functions:

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple. Using this function we can convert any sequence such as list to tuple.

>>>lst = ['c', 'b', 1, 2, 3.14, 'string']#converting the list to tuple
>>>t1 = tuple(lst)
>>>t1
('c', 'b', 1, 2, 3.14, 'string')

Thus from the above code the list “lst” is converted to tuple.

max() function:

  • The max() function will return the highest value among all the values in the tuple.
  • It returns an error if the tuple has multiple datatypes.

For example,

  • we will look to use the max() function to find the maximum price in the tuple named price.
>>>prices_tuple = (159.54, 37.13, 71.17)
>>>price_max = max(prices_tuple)
>>>print(price_max)
159.74

As the tuple “prices_tuple” have all numbers the largest value among the tuple is returned as output. But if the tuple has multiple datatypes that means holds heterogeneous data then it throws an error.

>>> prices_tuple = (159.54, 37.13, 71.17,"string")
>>> max(prices_tuple)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'float'

Here, we have tuple ”prices_tuple” with a string . As the tuple contains a string in it we cannot get a max value in the above tuple. If the tuple contains only strings then max value is returned based on the ASCII values.

min() function:

The min() function will return the lowest value of the inputted values.

  • The min() function will return the least value among all the values in the tuple.
  • It returns an error if the tuple has multiple datatypes/heterogeneous data.

For example,

  • we will look to use the min() function to find the minimum price in the tuple named prices_tuple.
>>>prices_tuple = (159.54, 37.13, 71.17) 
>>>price_min = min(prices_tuple)
>>>print(price_min)
37.13

As the tuple “prices_tuple” have all numbers the largest value among the tuple is returned as output. But if the tuple has multiple datatypes/heterogeneous data then it throws an error.

>>> prices_tuple = (159.54, 37.13, 71.17,"string")
>>> min(prices_tuple)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'float'

Here, we have tuple ”prices_tuple” with a string . As the tuple contains a string in it we cannot get a min value in the above tuple. If the tuple contains only strings then min value is returned based on the ASCII values.

Tuple Methods

Python has two built-in methods that you can use on tuples.

>>>t1 = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)>>>x = t1.count(5) # method>>>print(x)
2

The above code returns the number of times 5 is repeated in the tuple.

>>>thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)>>>x = thistuple.index(8)>>>print(x)
3

The index() method returns the index of the element specified.In above code, the index of value 8 is given as output.

Advantages of Tuple over List

Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:

  • We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.
  • Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance boost.
  • Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
  • If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.

--

--