All Courses
Python Tuples

Python Tuples

May 17th, 2019 python

Python Tuples

What is a Tuple in Python?

A tuple is a collection of Python objects that are ordered and unchangeable or immutable. Tuples are similar to a list in that, both have a sequence of elements that can be of different data types (integer, string, float, etc.). The difference between the two is that tuples cannot be changed. Once a tuple is created, its values cannot be updates or changed. A Tuple is same as lists used to store sequence of objects separated by comma enclosed with parentheses. The value of items stored in the list can be mutable while the tuple is immutable. Tuple is mainly used for to protect data.

Defining a Python

Tuples use parenthesis () unlike lists which use square brackets [] to hold elements. The parenthesis is optional; however, it is a good practice to use it. The elements are separated by using commas between them.

my_tuple1 = ("umbrella", "horse", 132, 14.5);
my_tuple2 = "sky", "hut", "bamboo", 16;
my_tuple3 = ("sticks", "stones")
my_tuple4 = (12, 34, 45)
print(my_tuple1)
print(my_tuple2)
print(my_tuple3)
print(my_tuple4)
Output
('umbrella', 'horse', 132, 14.5)
('sky', 'hut', 'bamboo', 16)
('sticks', 'stones')
(12, 34, 45)

Accessing values in a Tuple

An element or value in a tuple can be accessed by referring to the index of the element inside square brackets as shown below.

my_tuple1 = ("umbrella", "horse", 132, 14.5);
print(my_tuple1[1])
print(my_tuple1[3])
Output
horse
14.5
Similarly, you can also use negative or reverse indexing to access an item within a tuple. In the example below, [-1] refers to the last element within the tuple and [-2] refers to the last second item within the tuple.
my_tuple1 = ("umbrella", "horse", 132, 14.5);
print(my_tuple1[-1])
print(my_tuple1[-2])
Output
14.5
132

Looping through tuple elements

You can loop through the elements of a tuple by using the for loop.

my_tuple = ("coconut", "pineapple", "papaya")
for x in my_tuple:
print(x)
Output
coconut
pineapple
papaya

Updating tuples

Tuples cannot be updated or changed but you can combine or concatenate tuples to create a new tuple which contains elements of existing tuples as well as new elements if you decide to add them. This can be done by using the plus + operator .

my_tuple1 = ("Mon", "Tue", "Wed");
my_tuple2 = ("Thursday", "Friday", "Saturday", "Sunday");
my_tuple3 = my_tuple1 + my_tuple2;
print (my_tuple3);
Output
('Mon', 'Tue', 'Wed', 'Thursday', 'Friday', 'Saturday', 'Sunday')
or
my_tuple1 = ("Mon", "Tue", "Wed");
my_tuple2 = my_tuple1+("Thursday", "Friday", "Saturday", "Sunday");
print (my_tuple2);
Output
(‘Mon’, ‘Tue’, ‘Wed’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Sunday’)

Deleting elements in a tuple

As tuple elements are immutable, you cannot delete individual elements in it. If you wish to delete an entire tuple, that is possible by using the del keyword. The following example shows an error after the tuple has been deleted because it no longer exists.

my_tuple1 = ("Mon", "Tue", "Wed");
print ("Before deleting tuple:", my_tuple1);
del my_tuple1;
print ("After deleting tuple:");
print (my_tuple1);
Output
Before deleting tuple: ('Mon', 'Tue', 'Wed')
After deleting tuple:
Traceback (most recent call last):
File "jdoodle.py", line 5, in <module>
print (my_tuple1);
NameError: name 'my_tuple1' is not defined

Checking if an item exists in a tuple

To check if an item or element exists within a tuple, you can specify the name of the element followed by the in keyword and tuple name.

my_tuple = ("cat", "dog", "mouse")
if "cat" in my_tuple:
print ("Yes, 'cat' is present in my_tuple")
Output
Yes, 'cat' is present in my_tuple

Check number of items in a tuple

You can find the number of items in a tuple by using the len() method.

my_tuple = ("cat", "dog", "mouse")
print("There are ", len(my_tuple), "items in my_tuple")
Output
There are  3 items in my_tuple

Multiplying or duplicating an item in a tuple

The items in a tuple can be multiplied by sing the multiplication operator * following the number of copies you want to make.

my_tuple = ("yes", "no")*3
print(my_tuple)
Output
('yes', 'no', 'yes', 'no', 'yes', 'no')
OR
If you want to multiply a specific item in a tuple, you should add a comma next to the item for the copies to be produced as individual items and for the item to be considered as a tuple and not a string.
my_tuple = ("yes!",)*3 + ("of course!",);
print(my_tuple)
Output
('yes!', 'yes!', 'yes!', 'of course!')

Slicing a tuple

A subset of elements can be chosen by using slicing. This can be done by specifying the index range.

Slice a tuple from a specified start and end range

Elements in a tuple can be sliced from a specified range. The start and end index are separated by a colon. The following example specifies that the element must start printing from index 0 and stop at index 3 where index 2 will be the last element to be printed. Similarly, you can also use backward indexing for the elements to start indexing from the last element.

my_tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
print(my_tuple[0:3])
print(my_tuple[:-5])
Output
('a', 'b', 'c')
('a', 'b', 'c')

Slice a tuple from a specified or unspecified start index till the last element

Elements can be sliced from a specified starting index till the last element as shown below with two colons after the start index. Otherwise, you can print all the elements by simply adding two colons without specifying any index before or after.

my_tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
print(my_tuple[3::])
print(my_tuple[::])
Output
('d', 'e', 'f', 'g', 'h')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')

Slice a tuple by printing alternate elements in a tuple

Elements in a tuple can be printed alternately or with a specified number of skips before printing the next element. This can be done by specifying the start index, end index and number o f elements to skip each time before printing the next element. In the example below, the element is specified to start from index 0 (which is ‘a’) and stop at index 7 (which is ‘h’). There is also another condition that specifies that it should skip the next element and print every second element after the printed element until the last specified index. The second element in this case begins with index 2 which is ‘c’ followed by the next second element which is index 4 (‘e’).

my_tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
print(my_tuple[0:7:2])
Output
('a', 'c', 'e', 'g')

Slicing a tuple in reverse order

Elements in a tuple can also be sliced to show in reverse by using backward indexing.

my_tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
print(my_tuple[::-1])
Output
('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')

Methods of Tuple in Python

Tuple count() method

The count() method can be used to count the number of occurrences of an element in a tuple.

my_tuple = ("Elise", "Gabriel", "Jen", "Mark", "Jen");
print("Elise:", my_tuple.count("Elise"))
print("Jen:" ,my_tuple.count("Jen"))
Output
Elise:1
Jen:2

Tuple index() method

The index() method can be used to return the position for a specified value. If there are more than one occurrences of a specified element, it would return the position for the first occurrence of the specified element.

my_tuple = ("Elise", "Gabriel", "Jen", "Mark", "Jen");
print("Elise:", my_tuple.index("Elise"))
print("Jen:" , my_tuple.index("Jen"))
Output
Elise:1
Jen:2

Tuple min() and max() method:

In order to return an element with maximum value, the max() function can be used. Likewise, in order to return an element with minimum value, the min() function can be used. While using integers, the max() and min() method returns the maximum and minimum integer respectively. While using letters, the max() function returns the string that begins with the further most letter in the alphabet starting from Z and moving down to Y,X,W and so forth, while the min() function returns the nearest letter starting from A and moving up to B,C,D and so on.

my_tuple = (1, 2, 3, 4, 6, 2, 5, 3, 8, 2);
print("Max value:", max(my_tuple))
print("Min value:", min(my_tuple))
my_tuple1 = ("mary", "mari", "zack");
print("Max value:", max(my_tuple1))
print("Min value:", min(my_tuple1))
Output
Max value: 8
Min value: 1
Max value: zack
Min value: mari
max method:
Example:
t = (200,300,100,400)
print(max(t))
Output:
400

Comparing tuples

We can compare two tuples with relational operators.

Example:
a=(5,2)b=(1,4)if (a>b):
print("a is bigger")
else:
print("b is bigger")
Output:
a is bigger

Length method

Example:
t = (200,300,100,400)
print(len(t))
Output:
4

Nesting of Tuples

You can add tuples within a tuple to create a nested tuple.

my_tuple1 = (14, 12);
my_tuple2 = ("Alex", "Connie");
my_tuple3 = (my_tuple1, my_tuple2);
print(my_tuple3)
Output
((14, 12), ('Alex', 'Connie'))

Converting a sequence to tuple

A sequence can be converted to tuple by using the tuple() function. The type() function can be used to check the data type. The following example converts a list to tuple.

my_list = ["Alex", "Connie"];
print(type(my_list))
my_tuple = tuple(my_list);
print(type(my_tuple))
Output
<class 'list'>
<class 'tuple'>

Tuple packing and unpacking

While packing, values are placed in a new tuple. While unpacking, those values are extracted back into variables.

x = ("Anne", 20, "Student")    # tuple packing
(name, age, occupation) = x    # tuple unpacking
print(name)
print(age)
print(occupation)
Output
Anne
20
Student

Using tuples as keys

Immutable elements can be used as dictionary keys. Since tuples are immutable, they can also be used as dictionary keys.

directory = {}
directory["Parker","Peter"] = 8012195311;
for lname,fname in directory:
print (fname, lname, directory[lname,fname])
Output

Peter Parker 8012195311

Slicing

We can acces a range of elements from a tuple by using colon (:).

Example
t = (200,300,100,400)
print(t[0:2])
print(t[2:4])
Output
(200, 300)

(100, 400)

Constructing Tuples

The construction of tuples uses () with elements separated by commas. For example:

Create a tuple

t = (1,2,3) u = 1.0+2j, 3.0+3j,"a","bb"
#mixed type of objects v = (1,1.0,2.0+3.0j,"a",["aa","bb"],(1.0,2.0,3.0),{1,2,3},{"a":1})#mixed type of objects with parenthesis enclosure
w = tuple()
print(type(t))
print(type(u))
print(type(v))
print(type(w))
<class 'tuple'="">
<class 'tuple'="">
<class 'tuple'="">
<class 'tuple'="">

Create another tuple from existing tuples u and v

w = u + v
print(w)
((1+2j), (3+3j), 'a', 'bb', 1, 1.0, (2+3j), 'a', ['aa', 'bb'], (1.0, 2.0,
3.0), {1, 2, 3}, {'a': 1})

Doesnt’ support item assignment

v[0] = t + u TypeError Traceback (most recent call last) in () —-> 1 v[0] = t + u TypeError: ‘tuple’ object does not support item assignment

lets verify the datatype for the above for element in w:

print( element ,type(element)) #the same can done with lists also.
(1+2j) <class 'complex'="">
 (3+3j) <class 'complex'="">
a <class 'str'="">
 bb <class 'str'="">
 1 <class 'int'="">
1.0 <class 'float'="">
 (2+3j) <class 'complex'="">
 a <class 'str'="">
 ['aa', 'bb'] <class 'list'="">
 (1.0, 2.0, 3.0) <class 'tuple'="">
{1, 2, 3} <class 'set'="">
 {'a': 1} <class 'dict'="">

creating tuple from another tuple

#Slicing is supported print(t[1])
Indexing u[2] = "aa"
TypeError
Traceback (most recent call last)  in ()
print(t[1])
Indexing ----> 4 u[2] = "aa"
TypeError: 'tuple' object does not support item assignment

The tuple contains nested tuples

 t1 = ("apple", 3, 1.4, ("banana", 5))
 for element in t1: print( element ,type(element))
apple <class 'str'="">
 3 <class 'int'="">
1.4 <class 'float'="">
 ('banana', 5) <class 'tuple'="">
  • check the membership of an element in a tuple
  • in operation is used to check the membership
  • membership is true if the value is present else false
t1 = ("apple", "banana", "cherry","apple")
print( "banana" in t1 )
print( "orange" in t1 )
print( "banana" not in t1 )
True
False
False

Tuples have built-in methods, but not as many as lists do. Let’s look at two of them:

  • Use .index to enter a value and return the index
  • Use .count to count the number of times a value appears
print(t1.index('apple'))
print("count is {}".format(t1.count('apple')))
count is 2
Note:
  • I would recommend always using parentheses
  • to indicate start and end of tuple
  • even though parentheses are optional.
  • Explicit is better than implicit.
zoo = 'python', 'elephant', 'penguin'
print('Number of animals in the zoo is',
len(zoo))
new_zoo = 'monkey', 'camel', zoo
print('Number of cages in the new zoo is',
len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',
len(new_zoo)-1+len(new_zoo[2]))
Output :
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant',
'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5

Advantages of using Tuples over a List

Tuples and lists both have their own advantages. Here, we look at the advantages of using tuples over a list. Some of the advantages are as follows:

  • As tuples are immutable, iterating through a tuple would be much faster as compared to a list.
  • Tuples which consist of immutable elements can be used as keys for a dictionary. This is not possible with a list.
  • If you have data that doesn’t change, using a tuple can ensure that it is write-protected.
Social Share:

0 responses on "Python Tuples"

Leave a Message

Your email address will not be published. Required fields are marked *