If there is only a single element in a tuple then the element should be followed by a comma.
Note : If we assign the value without comma it is treated as integer.
A sequence of without parenthesis i.e. values separated with comma is treated as tuple by default.
Accessing Elements in a Tuple
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it has been created. An attempt to do this would lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
Elements of Tuple is Mutable (If element is a list)
An element of a tuple may be of mutable type, e.g., a list.
# 4th element of the tuple2 is a list
>>> tuple2 = (1,2,3,[8,9])
# modify the list element of the tuple tuple2
>>> tuple2[3][1] = 10
# modification is reflected in tuple2
>>> tuple2
(1, 2, 3, [8, 10])
Tuple Operations
1. Concatenation (+)
Python allows us to join tuples using concatenation operator depicted by symbol +.
# concatenates two tuples
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Create a new tuple which contains the result of this concatenation operation.
Concatenation operator can also be used for extending an existing tuple. When we extend a tuple using concatenation a new tuple is created.
# single element is appended to tuple6
>>> tuple6 = (1,2,3,4,5)
>>> tuple6 = tuple6 + (6,)
>>> tuple6
(1, 2, 3, 4, 5, 6)
# more than one elements are appended
>>> tuple6 = tuple6 + (7,8,9)
>>> tuple6
(1, 2, 3, 4, 5, 6, 7, 8, 9)
2. Repetition / Replication Operator *
Repetition operation is depicted by the symbol *. It is used to repeat elements of a tuple. We can repeat the tuple elements. The repetition operator requires the first operand to be a tuple and the second operand to be an integer only.
3. Membership operator [ in and not in ]
in : The in operator checks if the element is present in the tuple and returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
not in : The not in operator returns True if the element is not present in the tuple, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' not in tuple1
False
4. Slicing
Slicing means extracting the parts of list. Like string and list, slicing can be applied to tuples in the same way.
Forward Slicing
Backward Slicing / Negative Indexing
1. len() : Returns the length or the number of elements of the tuple passed as the argument
>>> tuple1 = (10,20,30,40,50)
>>> len(tuple1)
5
2. tuple() : Creates an empty tuple if no argument is passed. Creates a tuple if a sequence is passed as argument
>>> tuple1 = tuple()
>>> tuple1
( )
>>> tuple1 = tuple(‘aeiou’) #string
>>> tuple1
(‘a’, ‘e’, ‘i’, ‘o’, ‘u’)
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
3. count() : Returns the number of times the given element appears in the tuple.
>>> tuple1 = (10,20,30,10,40,10,50)
>>> tuple1.count(10)
3
>>> tuple1.count(90)
0
4. index() : Returns the index of the first occurrence of the element in the given tuple.
>>> tuple1 = (10,20,30,40,50)
>>> tuple1.index(30)
2
>>> tuple1.index(90)
ValueError: tuple.index(x): x not in tuple
5. sorted() : Takes elements in the tuple and returns a new sorted list. It should be noted that, sorted() does not make any change to the original tuple
tuple1 = (“Rama”,”Heena”,”Raj”,
“Mohsin”,”Aditya”)
sorted(tuple1)
[‘Aditya’, ‘Heena’, ‘Mohsin’, ‘Raj’,
‘Rama’]
6. min() : Returns minimum or smallest element of the tuple.
7. max() : Returns maximum or largest element of the tuple.
8. sum() : Returns sum of the elements of the tuple.
tuple1 = (19,12,56,18,9,87,34)
min(tuple1)
9
max(tuple1)
87
sum(tuple1)
235
Assignment of tuple is allows a tuple of variables on the left side of the assignment operator to be assigned respective values from a tuple on the right side. The number of variables on the left should be same as the number of elements in the tuple.
# The first element 10 is assigned to num1 and the second element 20 is assigned to num2.
>>> (num1,num2) = (10,20)
>>> print(num1)
10
>>> print(num2)
20
>>> record = ( “Pooja”,40,”CS”)
>>> (name,rollNo,subject) = record
>>> name
‘Pooja’
>>> rollNo
40
>>> subject
‘CS’
>>> (a,b,c,d) = (5,6,8)
ValueError: not enough values to unpack (expected 4, got 3)
Tuple Unpacking means, assigning values of tuple elements to different variables. Variables are written left of assignment operator separated by comma and tuple is written on the right side of assignment operator.
Be ensure, number of variables must be equal to the number of elements of tuple. Otherwise Python raise ValueError: not enough values to unpack.
>>> num1,num2 = (10,20)
>>> print(num1)
10
>>> print(num2)
20
>>> record = ( “Pooja”,40,”CS”)
>>> name, rollNo, subject = record
>>> name
‘Pooja’
>>> rollNo
40
>>> subject
‘CS’
>>> (a,b,c,d) = (5,6,8)
ValueError: not enough values to unpack (expected 4, got 3)
A tuple inside another tuple is called a nested tuple.
>>> nestedtuple = ( (1,2,3), (4,5,6), (7,8,9))
>>> nestedtuple
((1, 2, 3), (4, 5, 6), (7, 8, 9))
>>> nestedtuple[0]
(1, 2, 3)
>>> nestedtuple[1]
(4, 5, 6)
>>> nestedtuple[2]
(7, 8, 9)
>>> nestedtuple[0][0]
1
>>> nestedtuple[0][1]
2
>>> nestedtuple[2][1]
8
>>> print(nestedtuple)
((1, 2, 3), (4, 5, 6), (7, 8, 9))
Program : A program to create a nested tuple to store roll number, name and marks of students.
Output:
Program Write a program to swap two numbers without using a temporary variable.
# Program : Program to swap two numbers
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("\nNumbers after swapping:")
print("First Number:",num1)
print("Second Number:",num2)
Output:
Enter the first number: 5
Enter the second number: 10
Numbers before swapping:
First Number: 5
Second Number: 10
Numbers after swapping:
First Number: 10
Second Number: 5
Program : Write a program to compute the area and circumference of a circle using a function.
Output:
Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.400000000000002
Program : Write a program to input n numbers from the user. Store these numbers in a tuple. Print the maximum and minimum number from this tuple.
Output:
How many numbers do you want to enter?
5
98
10
12
15
The numbers in the tuple are:
(9, 8, 10, 12, 15)
The maximum number is:
15
The minimum
20 videos|20 docs|5 tests
|
|
Explore Courses for Humanities/Arts exam
|