Tuples: Tuples are used to store multiple items (may be of same type elements ie homogeneous data types or different types elements ie heterogeneous data types) in a single variable. It is a comma separated list of values enclosed in paranthesis ( ). Example:
tuple1=(2,3,4,5)
#tuple of homogeneous elements
tuple2=(“gargs”, 100, 24.56 )
#tuple of heterogeneous elements
tuple3=(“gargs” , “academy” , “Sonipat” , 9467863365)
#tuple of heterogeneous elements
tuple4=()
#empty tuple
Creating Tuples: We can create both empty tuples as well as non empty tuples by
1) directly assigning the literals/values and
2) by using the built in method tuple() of python.
Creating Empty Tuples by Directly Assigning: We can create empty tuples by assigning as:
>>> tuple1=() >>> tuple1 ()
Creating Empty Tuples in Python using tuple(): We can create empty tuples using tuple() in various ways as
>>> tuple2=tuple() >>> tuple2 () >>> tuple3=tuple(()) >>> tuple3 () >>> tuple4=tuple([]) >>> tuple4 () >>> tuple5=tuple({}) >>> tuple5 ()
Creating Non Empty Tuples in Python by assigning: We can create non empty tuples in various ways as
>>>#Creating homogeneous tuple >>> tuple1=(4,5,6,7) >>> tuple1 (4, 5, 6, 7) >>>#Creating heterogeneous tuple >>> tuple2=("garg", 100,45.67) >>> tuple2 ('garg', 100, 45.67)
Creating Non Empty Tuples in Python using tuple(): We can create non empty tuples in various ways as
>>>#creating tuple using list >>> tuple1= tuple([4,5,6,7]) >>> tuple1 (4, 5, 6, 7) >>>#creating tuple using tuple >>> tuple2=tuple(("garg", 100,45.67)) >>> tuple2 ('garg', 100, 45.67) >>>#creating tuple using string >>> tuple3=tuple("gargs academy") >>> tuple3 ('g', 'a', 'r', 'g', 's', ' ', 'a', 'c', 'a', 'd', 'e', 'm', 'y') >>>#Creating tuple using sets >>> tuple4=tuple({100,200,300,300}) >>> tuple4 (200, 100, 300) >>>#creating tuple using keys of dictionary >>> tuple5=tuple({1:2,3:4,5:4}) >>> tuple5 (1, 3, 5)
Immutable: Tuples are immutable objects ie. once created, we cant change the elements of the tuple.
>>> tuple1=(2,3,4) >>> tuple1[2]=20 Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> tuple1[2]=20 TypeError: 'tuple' object does not support item assignment >>> tuple1.append(10) Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> tuple1.append(10) AttributeError: 'tuple' object has no attribute 'append' >>> tuple1.remove(4) Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> tuple1.remove(4) AttributeError: 'tuple' object has no attribute 'remove'
Indexing on Python Tuples: We can access any element using its index as:
tuplename[valid_index]
Python supports 2-way indexing on lists: Forward Indexing and Backward Indexing.
Forward Indexing: In it, tuple elements are indexed from 0 to n-1 where n is the number of elements in the tuple.
>>> tuple2=("garg", 100,45.67) >>> tuple2 ('garg', 100, 45.67) >>> tuple2[2] 45.67
If the index does not exist, then an error message is shown as:
>>> tuple2=("garg", 100,45.67) >>> tuple2 ('garg', 100, 45.67) >>> tuple2[30] Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> tuple2[30] IndexError: tuple index out of range
Backward Indexing: In it, tuples are indexed from right side using negative indexes ie -1, -2, -3 and so on upto -n where n is the number of elements in the tuple.
>>> tuple1=(4,5,6,7) >>> tuple1[-1] 7 >>> tuple1[-3] 5
If the index does not exist, then an error message is shown as:
>>> tuple1=(4,5,6,7) >>> tuple1[-5] Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> tuple1[-5] IndexError: tuple index out of range
Tuples Operations: There are 4 types of operations possible on tuples.
1. Concatenations
2. Repetition
3. Membership
4. Slicing
5. Traversing
6. Deleting tuple
Concatenation/ Merging/Joining two tuples: We can join two tuples as:
tuplename1 + tuplename2
>>> tuple1=(2,3) >>> tuple1 (2, 3) >>> tuple2=(3,4,5) >>> tuple2 (3, 4, 5) >>> tuple1 + tuple2 (2, 3, 3, 4, 5) >>> tuple2 + tuple1 (3, 4, 5, 2, 3)
Elements of both the tuples will appear in the order, in which tuples are written i.e tuple1 + tuple2 will display elements of tuple1 before elements of tuple2 but tuple2 + tuple1 will display elements of tuples2 before elements of tuple1
>>> tuple1 + tuple2 (2, 3, 3, 4, 5) >>> tuple2 + tuple1 (3, 4, 5, 2, 3)
We can concatenate only a tuple with another tuple, otherwise python will report an error as:
>>> tuple1=(2,3) >>> tuple1 (2, 3) >>> tuple1 + 7 Traceback (most recent call last): File "<pyshell#42>", line 1, in <module> tuple1 + 7 TypeError: can only concatenate tuple (not "int") to tuple
Repetition: We can replicate or repeat the tuple multiple times as:
1) n * tuplename
2) tuplename *n
>>> tuple1=(3,4,5) >>> tuple1*2 (3, 4, 5, 3, 4, 5) >>> tuple1*3 (3, 4, 5, 3, 4, 5, 3, 4, 5)
To repeat or replicate the tuple, we can also write as:
>>> tuple1=(3,4,5) >>> 2*tuple1 (3, 4, 5, 3, 4, 5) >>> 3*tuple1 (3, 4, 5, 3, 4, 5, 3, 4, 5)
Membership on Tuples: In Python, there are two membership operators. (in, not in), which are used to test whether or not the value is present in the data sequence.
1) item in tuplename
2)item not in tuplename
>>> tuple1=(2,3,5) >>> 2 in tuple1 True >>> 4 in tuple1 False >>> 2 not in tuple1 False >>> 4 not in tuple1 True
in operator returns True only if the element is present as an individual element in the tuple
>>> tuple1=(2,3,(4,5)) >>> 4 in tuple1 False >>> (4,5) in tuple1 True
Slicing the tuples: To access a range of elements from a tuple, we can extract a part/slice of the tuple as:
tuplename[initial : final : step]
It will extract a part of the tuple from initial position upto final position (final position not included), in given step size.
default value of initial is 0, default value of final is n and default value of size is 1
>>> tuple1=(3,4,5,6,7,8,9) >>> tuple1[2:6:1] #starting from 2 upto 6 in steps of 1 (5, 6, 7, 8) >>> tuple1[2:6] #starting from 2 upto 6 in default steps i.e. 1 (5, 6, 7, 8) >>> tuple1[2:6:2] #starting from 2 upto 6 in steps of 2 (5, 7) >>> tuple1[0:] #starting from 0 upto default ie n=7 in default steps ie 1 (3, 4, 5, 6, 7, 8, 9) >>> tuple1[:] #starting from default ie 0 upto default ie n=7 in default steps ie 1 (3, 4, 5, 6, 7, 8, 9) >>> tuple1[:7] #starting from default ie 0 upto 7 in default steps ie 1 (3, 4, 5, 6, 7, 8, 9) >>> tuple1[:10] #starting from default ie 0 upto 10 in default steps ie 1 (3, 4, 5, 6, 7, 8, 9) >>> tuple1[::] #starting from default ie 0 upto default ie n=7 in default steps ie 1 (3, 4, 5, 6, 7, 8, 9) >>> tuple1[::-1] #starting from default ie 0 upto default ie n=7 in steps of -1 (9, 8, 7, 6, 5, 4, 3) #notice the tuple is reversed >>> tuple1[] #atleast a : is necessary SyntaxError: invalid syntax #even if you dont specify any initial, final or step value #otherwise error message will be shown as >>> tuple1(3) #notice [] are used in tuples for indexing, not () Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> tuple1(3) TypeError: 'tuple' object is not callable
Traversing a tuple using loops: We can traverse (ie. access or print or perform any other operation on each individual value of the tuple exactly once) the tuples using loops as:
>>> tuple1=(2,4,5,6) >>> for val in tuple1: print(val) 2 4 5 6
>>> tuple1=(2,4,5,6) >>> sum=0 >>> for val in tuple1: sum=sum+val >>> print(sum) 17 >>> avg=sum/len(tuple1) >>> print(avg) 4.25
del : It is used to delete the tuple entirely.
>>> tuple1=(3,4,5,7) >>> del tuple1 >>> tuple1 Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> tuple1 NameError: name 'tuple1' is not defined
Since tuples are immutable, we cant delete an item from a tuple.
>>>tuple1=(2,3,4,5) >>> del tuple1[3] Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> del tuple1[3] TypeError: 'tuple' object doesn't support item deletion
Applying built in functions on Tuples in Python: Built in functions are predefined functions in python that are available for use without the need for importing any module. We can apply various built in functions on tuples such as len(), tuple(), sum(), min(), max(), type(), id(), sorted() , del() etc.
len() is used to find the number of elements of the tuple.
>>> tuple1=(4,5,6,7,6) >>> tuple1 (4, 5, 6, 7, 6) >>> len(tuple1) 5 >>> tuple2=() >>> tuple2 () >>> len(tuple2) 0
tuple() : It is used to create tuples.
>>> tuple1=() >>> tuple1 () >>> tuple2=tuple() >>> tuple2 () >>> tuple3=tuple(()) >>> tuple3 () >>> tuple4=tuple([]) >>> tuple4 () >>> tuple5=tuple({}) >>> tuple5 () >>> tuple6=(4,5,6,7) >>> tuple6 (4, 5, 6, 7) >>> tuple7=("garg", 100,45.67) >>> tuple7 ('garg', 100, 45.67)
sum() is used to find the sum of elements of the tuple.
>>> tuple1=(4,5,6,7,6) >>> tuple1 (4, 5, 6, 7, 6) >>> sum(tuple1) 28
If the tuple elements are incompatible for addition, then an error message is shown as:
>>> tuple2=["garg","academy",9467863365] >>> sum(tuple2) Traceback (most recent call last): File "<pyshell#74>", line 1, in <module> sum(tuple2) TypeError: unsupported operand type(s) for +: 'int' and 'str'
min() is used to find the minimum from the elements of the tuple.
>>> tuple1=(4,5,6,7,6) >>> tuple1 (4, 5, 6, 7, 6) >>> min(tuple1) 4
If the tuple elements are incompatible for finding minimum, then an error message is shown as:
>>> tuple2=["garg","academy",9467863365] >>> min(tuple2) Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> min(tuple2) TypeError: '<' not supported between instances of 'int' and 'str'
max() is used to find the maximum from the elements of the tuple.
>>> tuple1=(4,5,6,7,6) >>> tuple1 (4, 5, 6, 7, 6) >>> max(tuple1) 7
If the tuple elements are incompatible for finding maximum, then an error message is shown as:
>>> list2=["garg","academy",9467863365] >>> max(list2) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> max(list2) TypeError: '>' not supported between instances of 'int' and 'str'
type() is used to find the data type of the object passed as an argument.
>>> tuple1=(3,4,5) >>> tuple1 (3, 4, 5) >>> type(tuple1) <class 'tuple'>
id() is used to find the address or location where the first element of the tuple is stored in memory.
>>> tuple1=(3,4,5) >>> tuple1 (3, 4, 5) >>> id(tuple1) 2021591639552
sorted(): It is used to create a list from the elements of a given tuple in sorted order.
>>> tuple1=(3,4,2,1) >>> sorted(tuple1) [1, 2, 3, 4]
We can also store the result in a list variable as:
>>> tuple1=(3,4,2,1) >>> list1=sorted(tuple1) >>> list1 [1, 2, 3, 4] >>> list2=sorted(tuple1,reverse=True) >>> list2 [4, 3, 2, 1]
But the original tuple remains unchanged.
>>> tuple1 ([3, 4, 2, 1)
del() : It is used to delete the tuple entirely.
>>> tuple1=(3,4,5,7) >>> del(tuple1) >>> tuple1 Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> tuple1 NameError: name 'tuple1' is not defined
Since tuples are immutable, we cant delete an item from a tuple.
>>>tuple1=(2,3,4,5) >>> del (tuple1[3]) Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> del (tuple1[3]) TypeError: 'tuple' object doesn't support item deletion
Tuples Functions in Python: Since Tuples are immutable objects, So we cant add or remove or change the order of elements in a tuple. So functions like append(), extend(), insert(), pop(), remove(), clear(), sort() and reverse() etc can’t be applied on tuples. We can apply various other functions on tuples such as:
- count()
- index()
To see a list of all functions of a tuple:
>>> dir(tuple) ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
To see a description of all the functions of the tuple:
>>> help(tuple) Help on class tuple in module builtins: class tuple(object) | tuple(iterable=(), /) | | Built-in immutable sequence. | | If no argument is given, the constructor returns an empty tuple. | If iterable is specified the tuple is initialized from iterable's items. | | If the argument is a tuple, the return value is the same object. | | Built-in subclasses: | asyncgen_hooks | UnraisableHookArgs | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return value*self. | | count(self, value, /) | Return number of occurrences of value. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) from builtins.type | See PEP 585 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature.
count(): To count the frequency of an item in the tuple.
>>> tuple1=(4,5,6,7,6) >>> tuple1.count(6) 2
If the element does not exist in the tuple, it returns 0
>>> tuple1=(4,5,6,7,6) >>> tuple1.count(30) 0
index(): It is used to find the index position of first occurrence of an item in the tuple.
>>> tuple1=(4,5,4,7,6) >>> tuple1.index(4) 0
If the item is not present in the tuple, it will result into an error as:
>>> tuple1=(4,5,6,7,6) >>> tuple1.index(30) Traceback (most recent call last): File "<pyshell#93>", line 1, in <module> tuple1.index(30) ValueError: tuple.index(x): x not in tuple
Nested tuples: We can create a tuple having another tuple as its elements as:
>>> tuple1=(3,4,(5,6,7,4),3) >>> tuple1 (3, 4, (5, 6, 7, 4), 3)
We can create as many levels of nesting as we want as shown :
>>> tuple1=(3,4,(5,6,7,(5,6,9),4),3) >>> tuple1 (3, 4, (5, 6, 7, (5, 6, 9), 4), 3)
We can access elements of nested tuples by using multiple indexes as:
>>> tuple1=(3,4,(5,6,7,(5,6,9),4),3) >>> tuple1 (3, 4, (5, 6, 7, (5, 6, 9), 4), 3) >>> tuple1[0] 3 >>> tuple1[2][0] 5 >>> tuple1[2][3][1] 6
Types of Nested Tuples: There are 2 types of nested tuples:
1) Regular Tuples
2) Ragged Tuples
Regular Tuples: These are the tuples whose all elements have same shape/size/number of elements. Example
>>> tuple1=((2,3,4),(4,5,6),(7,8,9)) >>> tuple1 ((2, 3, 4), (4, 5, 6), (7, 8, 9))
Ragged Tuples: These are the tuples whose all elements don’t have same shape/size/number of elements. Example
>>> tuple1=((2,3,4),(4,5,6),(7,8)) >>> tuple1 ((2, 3, 4), (4, 5, 6), (7, 8))
Suggested programs: Program 1: finding the maximum, minimum, mean of numeric values stored in a tuple
tuple1=eval(input("Enter the tuple")) print("The tuple is") print(tuple1) mx=max(tuple1) print("The maximum no in the tuple is" ,mx) mn=min(tuple1) print("the minimum no in the tuple is",mn) sum=0 for val in tuple1: sum=sum + val print("The sum of the numbers in the tuple is", sum) n=len(tuple1) avg=sum/n print("the average of the numbers in the tuple is" , avg)
Output :
Enter the tuple(3,4,5,2) The tuple is (3, 4, 5, 2) The maximum no in the tuple is 5 the minimum no in the tuple is 2 The sum of the numbers in the tuple is 14 the average of the numbers in the tuple is 3.5
Suggested programs: Program 2: linear search on tuple of numbers
tuple1=eval(input("Enter the tuple")) no=int(input("Enter the number to find")) print("The tuple is") print(tuple1) n=len(tuple1) for i in range(n): if no==tuple1[i]: print(no , " Found at location", i+1) break else: print(no, " Not found in the tuple")
Output 1:
Enter the tuple(2,3,4,1,6) Enter the number to find3 The tuple is (2, 3, 4, 1, 6) 3 Found at location 2
Output 2:
Enter the tuple(2,3,4,2) Enter the number to find30 The tuple is (2, 3, 4, 2) 30 Not found in the tuple
Suggested programs: Program 3: counting the frequency of elements in a tuple
tuple1=eval(input("Enter the tuple")) no=int(input("Enter the number to find frequency")) print("The tuple is") print(tuple1) n=tuple1.count(no) print(no, " appears in the tuple " ,n , " times")
Output 1:
Enter the tuple(3,4,5,2,3) Enter the number to find frequency 3 The tuple is (3, 4, 5, 2, 3) 3 appears in the tuple 2 times
Output 2:
Enter the tuple(3,4,5,2,3) Enter the number to find frequency 30 The tuple is (3, 4, 5, 2, 3) 30 appears in the tuple 0 times