Tuple
Tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses whereas lists use square brackets.
Creating atuple is as simple as puttingdifferent comma-separated values. Optionally, you can put these comma-separated values between parentheses. For eg,
tup1 = (‘physics’, ‘chemistry’, 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = “a”, “b”, “c”, “d”
The empty tuple is written as two parentheses containing nothing. tup1 = ();
To create a tuple containing a single value, we have to include a comma even though there is only one value.
tup1 = (50,)
Like string indices, tuple indices start at 0 and they can be sliced and concatenated
Accessing values in Tuples:
tup1 = (‘physics’, ‘chemistry’, 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print (“tup1[0]: “, tup1[0])
print (“tup2[1:5]: “, tup2[1:5])
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index. For eg,
When the above code is executed, it produces the following result, tup1[0] : physics
tup2[1:5] : [2, 3, 4, 5]
Tuple Assignment :
>>> a, b = 3, 4
>>> print a 3
>>> print b 4
>>> a, b, c = (1,2,3), 5, 6
>>> print a (1, 2, 3)
>>> print b 5
>>> print c 6
Once in a while, it is useful to perform multiple assignments in a single statement and this can be done with tuple assignment:
>>> a, b, c, d = 1, 2, 3
ValueError: need more than 3 values to unpack
The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.
The number of variables on the left and the number of values on the right have to be the same:
Such statements can be useful shorthand for multiple assignment statements, but care should be taken that it does not make the code more difficult to read.
One example of tuple assignment that improves readability is when we want to swap the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:
temp = a a = b
b = temp
If we have to do this often, such an approach becomes cumbersome. Python provides a form of tuple assignment that solves this problem neatly:
Tuples as return values :
def swap(x, y):
return y, x
Functions can return tuples as return values. For example, we could write a function that swaps two parameters:
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
def swap(x, y):
x, y = y, x
In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake:
If we call swap like this swap(a, b)
then a and x are aliases for the same value. Changing x inside swap makes x refer to a different value, but it has no effect on a in main. Similarly, changing y has no effect on b. This function runs without producing an error message, but it doesn’t do what we intended. This is an example of a semantic error.
Basic tuples operations, Concatenation, Repetition, in Operator, Iteration :
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the previous chapter.
Python Expression | Results | Description |
len((1, 2, 3)) | 3 | Length |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | Concatenation |
(‘Hi!’,) * 4 | (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) | Repetition |
3 in (1, 2, 3) | True | Membership |
for x in (1,2,3) : print (x, end=’ ‘) | 1 2 3 | Iteration |
Built-in Tuple Functions :
SN | Function with Description |
1 | cmp(tuple1, tuple2) No longer available in Python 3. |
2 | len(tuple) Gives the total length of the tuple. |
3 | max(tuple) Returns item from the tuple with max value. |
4 | min(tuple) Returns item from the tuple with min value. |
5 | tuple(seq) Converts a list into tuple. |
Python includes the following tuple functions-
Tuplelen()MethodDescription
The len() method returns the number of elements in the tuple.
Syntax
Following is the syntax for len() method- len(tuple)
Parameters
tuple – This is a tuple for which number of elements to be counted.
Return Value
This method returns the number of elements in the tuple.
Example
The following example shows the usage of len() method. tuple1, tuple2 = (123, ‘xyz’, ‘zara’), (456, ‘abc’)
print (“First tuple length : “, len(tuple1)) print (“Second tuple length : “, len(tuple2)) First tuple length : 3 Second tuple length : 2
When we run above program, it produces following result-
Tuple max() Method
Description
The max() method returns the elements from the tuple with maximum value.
Syntax
Following is the syntax for max() method- max(tuple)
Parameters
tuple – This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value.
Example
tuple1, tuple2 = (‘maths’, ‘che’, ‘phy’, ‘bio’), (456, 700, 200) print (“Max value element : “, max(tuple1))
print (“Max value element : “, max(tuple2))
The following example shows the usage of max() method. Max value element : phy Max value element : 700
Tuple min() Method
Description
The min() method returns the elements from the tuple with minimum value.
Syntax
Following is the syntax for min() method- min(tuple)
Parameters
tuple – This is a tuple from which min valued element is to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
Example
tuple1, tuple2 = (‘maths’, ‘che’, ‘phy’, ‘bio’), (456, 700, 200) print (“min value element : “, min(tuple1))
print (“min value element : “, min(tuple2))
The following example shows the usage of min() method.
When we run the above program, it produces the following result- min value element : bio min value element : 200
Tuple tuple() Method Description
The tuple() method converts a list of items into tuples.
Syntax
Following is the syntax for tuple() method- tuple( seq )
Parameters
seq – This is a tuple to be converted into tuple.
Return Value
This method returns the tuple.
Example
The following example shows the usage of tuple() method. list1= [‘maths’, ‘chemistry’, ‘phy’, ‘bio’] tuple1=tuple(list1) print (“tuple elements : “, tuple1)
tuple elements : (‘maths’, ‘chemistry’, ‘phy’,’bio’)
When we run the above program, it produces the following result