
Tuples in Python | CBSE Class 11| Computer Science
Dear Class 11th STUDENTS, ! Welcome to this tutorial of Tuples in Python from your CBSE class 11 of Computer Science Syllabus .
In this tutorial, we shall be learning our chapter-6: Tuples in Python from Unit 2: Programming and Computational Thinking (PCT-1) as CBSE BOARD suggested to learn about computer system and its organisation to complete this section.
Unit 2: Programming and Computational Thinking (PCT-1)
Chapter 10 :Tuples in python:
- introduction,
- Indexing,
- Tuple operations (concatenation, repetition, membership and slicing);
- Built-in functions/methods – len(), tuple(), count(), index(), sorted(), min(), max(), sum();
- Tuple assignment,
- Nested tuple;
- suggested programs: finding the minimum, maximum, mean of values stored in a tuple; linear search on a tuple of numbers, counting the frequency of elements in a tuple.
I advice you to check the latest syllabus given by CBSE Board at its Official website: www.cbseacademic.nic.in
Also, in this tutorial we will covers all necessary topics/concepts required to complete your exams preparations in CBSE classes 11th.
Also, you can Sign Up our free Computer Science Courses for classes 11th and 12th.
NOTE:
- We are also giving some important Questions & Answers for better understanding as well as preparation for your examinations.
- You may also download PDF file of this tutorial from our SHOP for free.
- For your ease and more understanding, we are also giving the video explanation class of each and every topic individually, so that you may clear your topics and get success in your examinations.
INTRODUCTION
The Python tuples are sequence that are used to store a tuple of values of any type. You have learnt in earlier chapters that Python tuples are immutable i.e., you cannot change the element of a tuple in place; Python will create a fresh tuple when you make changes to an element of a tuple. Tuple is a type of sequence like strings and lists but it differs from them in the way that lists are mutable but strings and tuples are immutable.
This chapter is dedicated to basic tuple manipulation in python. We shall be talking about creating and accessing tuples, various tuple operation and tuple manipulations through some built-in functions.
CREATING AND ACCESSING TUPLES
A tuple is a standard data type of python that can store a sequence of values belonging to any type. The Tuple are depicted through parentheses i.e., round brackets, e.g., following are some tuples in python:
Before we proceed and discuss how to create tuples, one thing that must be clear is that Tuple are immutable (i.e., non-modifiable) i.e., you cannot change elements of a tuple in place
Creating Tuples
Creating a tuple is similar to list creation, but here you need to put a number of expressions in parentheses. That is, use round brackets to indicate the start and end of the tuple, and separate the items by commas. For example:
(2, 4, 6)
(‘abc’ , ‘def)
(1,2, 0,3, 4.0)
( )
Thus, to create a tuple you can write in the form given below:
T = ( )
T = (value, …)
This construct is known as a tuple display construct. Consider some more examples:
The Empty Tuple
The empty tuple is ( ). It is the tuple equivalent of 0 or ‘’ . You can also create an empty tuple as:
T = tuple ()
It will generate an empty tuple and name that tuple as T.
Single Element Tuple
Making a tuple with a single element is tricky because if you just give a single element in round brackets, Python considers it a value only.
Example
To construct a tuple with one element just add a comma after the single element as shown below:
Long tuples
If a tuple contains many elements, then to enter such long tuples, you can split it across several lines, as given below:
Sqrs = ( o, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625)
Notice the opening parenthesis and closing parenthesis appear just in the beginning and end of the tuple.
Nested tuples
If a tuple contains an element which is a tuple itself then it is called nested tuple e.g., following is a nested tuple:
t 1 = (1, 2, (3, 4))
The tuple t1 has three elements in it: 1, 2 and (3, 4). The third element of tuple t1 is a tuple itself, hence, t1 is a nested tuple.
Creating Tuples from Existing Sequences
You can also use the built-in tuple type object (tuple ()) to create tuples from sequences as per the syntax given below :
T= tuple (<sequence>)
Where <sequence> can be any kind of sequence object including strings, lists and tuples.
Python creates the individual elements of the tuple from the individual elements of passed sequence. If you pass in another tuple, the tuple function makes a copy.
Consider following examples:
You can use this method of crating tuples of single characters or single digits via keyboard input. Consider the code below:
See, with tuple ( ) around input( ), even if you not put parenthesis, it will create a tuple using individual characters as elements. But most commonly used method to input tuples is eval (input ()) as shown below:
tuple = eval (input (‘’Enter tuple to be added:’’))
print (‘’Tuple you entered : ‘’, tuple )
when you execute it, it will work somewhat like:
Enter tuple to be added : (2, 4, ‘’a’’, ‘’hjkj1’’, [3,4])
Tuple you entered: (2, 4, ‘’a’’, ‘’hjkj1’’, [3,4] )
If you are inputting a tuple with eval ( ), then make sure to enclose the tuple elements in parenthesis.
Please not sometimes (not always) eval ( ) does not work in Python shell. At that time , you can run it through a script too.
Accessing Tuples
Tuples are immutable (non-editable) sequences having progression of elements. Thus, other than editing items, you can do all that you can do with lists. Thus, like lists, you can access its individual element. Before we talk about that, let us learn about how elements are indexed in tuples.
Similarity with Lists
Tuples are very much similar to lists except for the mutability. In other words, Tuples areImmutable counter-parts of lists. Thus, like lists, tuple-elements are also indexed, i.e., forward Indexing as 0,1, 2, 3, ….and backward indexing as -1, -2, -3,…. [see figure below]
Thus, you can access the tuple elements just like you access a lists or a string’s elements e.g., Tuple [i] will give you elements at ith index; Tuple [a-b] will give you elements between indexes a to b -1 and so on. Put in other words, tuples are similar to lists in following ways:
- Function len (T) returns the number of items (count) in the tuple T.
- Indexing and Slicing
T[i] returns the item at index i (the first item has index 0),
T[i: j] returns a new tuple, containing the objects between i and j excluding index j,
T [i:j : n] returns a new tuple, containing every nth item from index i to j , excluding index j Just like lists.
- Membership operators. Both ‘in’ and ‘not in’ operators work on Tuples just like they work for other sequences. That is, in tells if an element is present in the tuple or not and not in does the opposite.
- Concatenation and Replication operators + and *. The + operator adds one tuple to the end of another. The * operators repeat a tuple. We shall be talking about these two operations in a later section 12.3- Tuple Operators.
Accessing individual Elements
As mentioned, the individual elements of a tuple are accessed through their indexes given in square brackets, Consider the following examples:
>>>Vowels = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’ )
>>>Vowels [0]
‘a’
>>>Vowels [4]
‘u’
>>>Vowels [-1]
‘u’
>>>Vowels [-5]
‘a’
Recall that like strings, if you pass in a negative index, python adds the length of the tuple to the index to get its forward index. That is, for a 6- element tuple T, T[-5] will be internally computed as :
T [-5 + 6 [1], and so on.
Difference from lists
Although tuples are similar to lists in many ways, yet there is an important difference in mutability of the two. Tuple are not mutable, while lists are. You cannot change individual elements of a tuple in place, but lists allow you to do so.
That is, following statement is fully valid for lists (BUT not for tuple). That is, if we have a list L and a tuple T, then
L [i] = element
Is VALID for lists. BUT
T [i] = element
Is INVALID as you cannot perform item-assignment in immutable types.
Traversing Tuple
Recall that traversal of sequence means accessing and processing each element of it. Thus traversing a tuple also means the same and same is the tool for it, i.e.; the python loops. The for loop makes it easy to traverse or loop over the items in a tuple, as per following syntax:
For < item> in < Tuple> :
process each item here
For example, following loop shows each item of a tuple T in separate lines :
T = (‘p’ ,’y’, ‘t’, ‘h’, ‘o’, ‘n’)
for a in T
print (T [a] )
The above loop will produce result as:
P
y
t
h
o
n
How it works
The loop variable a in above loop will be assigned the Tuple elements, one at a time. So, loop- variable a will be assigned ‘p’ in first iteration and hence ‘p’ will be printed; in second iteration, a will get ‘y’ and ‘y’ will be printed; and so on.
If you only need to use the indexes of elements to access them, you can use functions range ( ) and len ( ) as per following syntax:
For index in range (len (t)):
process Tuple [index] here
Consider program 12.1 that traverse through a tuple using above format and prints each item of a tuple in separate lines along with its index.
TUPLE OPERATIONS
The most common operations that you perform with tuple include joining tuples and slicing tuples. In this section, we are going to talk about the same.
Joining Tuples
Joining two tuples is very easy just like you perform addition, literally;] the + operator, the concatenation operator, when used with two tuples, joins two tuples.
Consider the example given below:
As you can see that the resultant tuple has firstly elements of first tuple Ist 1 and followed by elements of second tuple Ist2. You can also join two or more tuples to form a new tuple, for example
The + operator when used with tuples requires that both the operands must be of tuple types.
You cannot add a number or any other value to a tuple. For example, following expressions will result into error:
Consider the following examples:
Notice
Sometimes you need to concatenate a tuple easy [say tpl] with another tuple containing only one element. In that case, if you write statement like
>>> Tpl + [3]
Python will return an error like:
:
Type Error: can only concatenate tuple [not “int”] to tuple
The reason for above error is that a number enclosed in [ ] is considered number only. To make it a tuple with just add a comma after the only element, i.e., make it [3,]. Now python won’t return any error and successfully concatenate the two tuples.
Repeating or replicating Tuples
Like strings and lists, you can use * operator to replicate a tuple specified number of times, e, g., if tp11 is [1, 3, 5], then
Slicing the Tuples
Tuple slices, like list –slices or string slices are the sub parts of the tuple extracted out. You can use indexes of tuple elements to create tuple slices as per following format:
seq = T [start: stop]
The above statement will create a tuple slice namely seq having elemants of tuple T on indexes start, start+1, start+2… Stop -1 Recall that index on last limit is not included in the tuple slice. The tuple slice is a tuple in itself that is you can perform all operations on it just like you perform tuples. Consider the following example:
>>>tpl = [10, 12, 14, 20, 22, 24, 30, 32, 34,]
>>>seq = tpl [3:-3]
>>>seq
[20, 22, 24]
For normal indexing, if the resulting index is outside the tuple, python raises an indexError exception. Slices are treated and boundaries instead, and the result will simply contain all items between the boundaries. For the start and stop given beyond tuple limits in a tuple slice, python simply returns the elements that fall between specified boundaries, if any .
Tuples also support slice steps too .that is , if you want to extract ,not consecutive but every other element of the tuple, there is a way out –the slice steps .the slice step are used as per following format:
Seq = T [start: step]
Consider some example to understand this.
Consider some more example :
seq = T [ : : 2 ] # get every other item , starting with the first
seq = T [ 5 : : 2 ] # get every other item , starting with the
# sixth element , i .e. , index 5
You can use the + and * operators with tuple slices too. For example, if a tuple namely tp values as [2, 4, 5, 7, 8, 9, 11, 12, 34], then:
Comparing Tuples
you can compare two tuples without having to write code with loops for it. For comparing two tuples, you can using comparison operators, i.e., <, >, =, !=etc . For comparison purposes, python internally compares individual elements of two tuples, applying all comparison rules that you have read earlier. Consider following code:
Unpacking Tuples
Creating a tuple from a set of values is called packing and its reverse, i.e., creating individual values from a tuple’s elements is called unpacking.
Unpacking is done as per syntax:
<variable1>, <variable2 >, <variable3>,… = t
Where the number of variables in the left side of assignment must match the number of elements in the tuple.
For example, if we have a tuple as :
T = (1, 2, ‘A’, ‘B’ )
The length of above tuple t is 4 as there are four elements in it . now to unpack it, we can write:
Python will now assign each of the elements of tuple t to the variables on the left side of assignment operator. That is, you can now individually print the values of these variables, somewhat like:
Print (w)
Print (x)
Print (y)
Print (z)
The above code will yield the result as :
1
2
‘A’
‘B’
As per Guido van Rossom, the creator of python language –
Deleting Tuples
The del statement of python is used to delete elements and objects but as you Know that tuples are immutable, which also means that individual elements of a tuple cannot be deleted, i.e., if you give a code like:
>>>del t1 [2]
Then python will give you a massage like:
Trackback (most recent call last) :
File “<ipython-input-83-card7b2ca8ce3>”, line 1, in<module>
del t1 [2]
TypeError : ‘tuple’ object doesn’t support item deletion
But you can delete a complete tuple with del statement as :
Del<tuple_name>
For example,
TUPLE FUNCTIONS AND METHODS