0% found this document useful (0 votes)
20 views13 pages

Unit-2 ch-12 Tuples

Uploaded by

kakalachu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views13 pages

Unit-2 ch-12 Tuples

Uploaded by

kakalachu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter-12

Tuples

Tuple
➢ It is a data structure like lists. It is sequence of values, ordered collection of objects separated
by comma enclosed in a normal bracket.
Color=( ‘red’, ‘blue’, ’green’)
➢ But unlike strings, which can only contain characters, tuples can contain elements of any type.
➢ The elements in a tuple are addressed by its index number. The index number starts from 0 to
n-1.
➢ Tuples are immutable, i.e. It cannot be changed after creation(read only)
➢ Tuples are good to use than lists because :
✓ Tuples are faster than lists. If you are defining a constant set of values and all you will do
with it is iterate through it, use a tuple instead of a list.
✓ Tuples make your code safer if you “write-protect” data that do not need to be changed.

Creating Tuple
➢ To create a tuple, we separate the elements with a comma and enclose them with a
parentheses()
➢ The syntax is:
tuple-variable = (val1, val2, val3, ....., valn)
➢ For example:

Examples :
Num = (67, 82, 98, 92, 78, 87, 82)
print (Num) # prints all elements (67, 82, 98, 92, 78, 87, 82)
WeekDays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday')
print (WeekDays) # prints ('Sunday', 'Monday', 'Tuesday', 'Wednesday')
Tup1 = (1,2,3,4)
Tup2 = () # empty tuple
Tup3 = ( 1,2,’red’,’blue’,4,5)
Tup4 = 1,2,3,4,5 # parenthesis is optional
Tup5 = ((1,2,3), (‘r’,’b’,’g’)) # can be nested
Tup6 = ([1,2,3]) # it may contain list
Tup7 = ((1,2,3),[4,5,6]) # contain both tuple and list

1|Page
➢ If a tuple is to be created with single item, then comma ( , ) is to be appended to distinguish a
tuple from a parenthesized expression. This is known as singleton tuple.
Otherwise it considered as integer element
Tup1 = ( 5 , )
or Tup1 = 5,

Tuples are immutable / Non-Changeable


➢ Tuples are immutable means that once a tuple is initialized, it is impossible to update individual
item in the tuple.
➢ Example :
x = ( 6,5,4,3,2,1)
x[3] = 300 # produces an error

Accessing Tuple Elements


➢ We can access tuple items by referring to the index number, inside square brackets.
➢ It is similae to lists.
➢ Python indexes tuple elements from left to right through positive indexing, with first element at
index 0 and from right to left through negative indexing, i.e. last element has index -1

2|Page
Creating an empty tuple using tuple function
➢ tup1 = tuple()
print ( tup1 ) displays ( )
➢ using tuple() , we can convert a sequence into tuple
➢ Example :
tup1 = tuple( “Hello” ) ( ‘H’, ‘e’, ‘l’, ‘l’, ‘o’)
tup2 = tuple ( [1,2,3,4] ) ( 1,2,3,4)

3|Page
Assigning values to a tuple
Tup3 = 1,2,3 ( 1,2,3)
Tup4 = Tup3

Focus on the id of tup and tup1, before and after changing tup

4|Page
Creating Singleton Tuple
Method 1 : >>> a = 1 ,
>>> a displays (1,)
Method 2 : >>> a = (1 , )
>>> a displays (1,)

Example to demonstate that no tuple is created if we skip comma ,


>>> b=([1,2,3]) # here, b is created as a list only because of absense of ,
>>> b[0]=5 # here, b is treated as a list because we have skipped comma after the
element in the tuple creation statement. Since, b is a list, it is mutable in
nature and when we b[0] = 5 , it updates the 0th element i.e. 1 to 5
>>> b
[5, 2, 3]
>>> c=[(1,2,3)] # tuple as an item of list
>>> c[0] = 5 # here, c is a list and c[0] is (1,2,3), when we write c[0] = 5, the entire
tuple which is present at 0th index, gets updated to 5
>>> c
[5]

Creating tuple by user input


t=tuple()
n=int(input("How many elements : "))
i=1
while i<= n:
a=input("Enter element : ")
t = t + (a,)
i=i+1
print(t)

5|Page
Nesting of tuples
t1 = (1,2,3,4)
t2 = (‘r’, ’b’, ’g’)
t3 = ( t1 , t2 )
print (t3) displays ( (1,2,3,4) , (‘r’,’b’,’g’) )
print (t3[0]) displays (1,2,3,4)
print (t3[1]) displays (‘r’ , ‘b’ , ‘g’)

Traversing through the tuple


Tuple can have both positive and negative index like list/string
Elements can be accessed by its index either from 0 to n-1 or -1 to -n

6|Page
Check if Item Exists in the tuple
➢ To determine if a specified item is present in a tuple use the in keyword:
➢ Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Output :
Yes, 'apple' is in the fruits tuple

Tuple Operations
1. Tuple slicing:
Tup1 = ( 1,2,3,4,5,6,7,8 )
print(tup1[5:]) displays (6,7,8)
print(tup1[2:5]) displays (3,4,5)

2. Tuple addition/concatenation
t1 = (1,2,3)
t2 = (4,5,6)
t3 = t1 + t2
print(t3) displays ( 1,2,3,4,5,6)

3. Tuple multiplication
t1 = (1,2,3)
t2 = t1 * 2
print(t2) displays ( 1,2,3,1,2,3)
7|Page
4. In and not in membership operator
4 in (1,2,3,4) displays True
5 in ( 1,2,3,4) displays False

Tuple Functions
1. len()
Returns the number of elements
Syntax : n=len(tup1)

2. count()
Returns the occurrence of a number in the tuple
Syntax : n=tup1.count(item)
Example :
tup1=( 1,2,3,2,4,2,3,5)
n=tup1.count(2) displays 3

3. any() : Returns True if tuple contains at least one element (non-zero) otherwise False
Example :
tup1=(1,2,3)
print(any(tup1)) displays True

8|Page
4. sorted() : it sorts the element and forms a list not a tuple
Example :
a = (4,2,6,7,1,3,9)
sorted(a) displays [1,2,3,4,6,7,9]
print(a) displays (4,2,6,7,1,3,9) i.e. original tuple

5. max() and min() : Returns the maximum or minimum value of tuple


Example 1 :
tup1=(1,2,3,4,5,6)
print( max(tup1) , min(tup1) ) displays 6,1
Note: Tuple should have same type of values
Example 2 :
fruit=(‘apple’)
max(fruit) or min(fruit) displays ‘p’ and ‘a’
In this case, fruit does not become a tuple because of absence of comma after the first
element ‘apple. So, it is treated as a string and max and min are found from the string, not
from the tuple.

9|Page
6. index() : returns index value of first occurrence of required element
Example :
a=(1,3,7,2,4,7,8,0)
print ( a.index (7) ) displays 2
print (a.index (7 , 3) displays 5 which is 2nd occurrence, as it
starts searching from index 3 which is
specified by the second parameter.

7. Comparing tuples by relational operator ( <, <=, >, >=, ==, !=) : we can compare
tuples. It displays True/False.

10 | P a g e
8. Deleting a tuple
del(tup) # deletes the complete tuple
we can not delete an element from tuple as it is immutable

9. zip() : it takes two or more sequences and zips them into a list of tuples. The tuple thus
formed has one element from each sequence.
For this, both the tuples should have same number of elements.
If lengths are not equal then smaller one will be considered.
Example :
tup1 = (1,2,3,4)
list1 = [‘a’, ’b’, ’c’, ’d’]
list2 = list ( zip(tup1, list1) ) produces [ (1,’a’), (2,’b’), (3,’c’), (4,’d’) ]

It is necessary to type cast the result to a tuple or list using tuple() or list(). zip() can be
used on 2 tuples, 2 lists or one tuple and one list.

If lengths are not equal then smaller one will be considered.


Example :
tup1=(1,2,3,4)
list1=[‘a’, ’b’, ’c’,]
list2 = list ( zip (tup1, list1 ) ) produces [ (1,’a’), (2,’b’), (3,’c’) ]

11 | P a g e
10. sum () : This function returns the sum of the elements of the tuple.
The elements in the tuple must be numeric otherwise an error is produced.
Example :
tup1 = (1,2,3,4)
print ( sum(tup1) ) displays 10

12 | P a g e
11. reversed () : The method is used to reverse a tuple and returns an iterator.
The method gets a return value and they will leave the original tuple unmodified.
Example :
Name = ['Anmol', 'Kiran', 'Vimal', 'Amit', 'Sidharth', 'Riya', 'Sneha']
Nm = reversed(Name) # Nm is an iterator
print (Nm) # prints: <reversed object at 0x024DCD50>
for i in Nm:
print (i, end=" ") # prints: Sneha Riya Sidharth Amit Vimal Kiran Anmol

Comparing List and Tuple

List Tuple
It uses more memory It uses less memory
It can not be used in dictionary as a key It can be used in dictionary as a key
We can add/ modify/delete an element We can not add/ modify/delete an element
It is mutable It is immutable
We can sort elements We can not sort ( it becomes list )

Advantages of Tuple over List:


1. Since Tuples are immutable, iterating through tuples is faster than list.
2. Tuples can be used as key in dictionary where list can not be.
3. Tuples are best suited for data where it is write-protected.
4. Multiple values can be returned from function by use of tuple.

13 | P a g e

You might also like