Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Tuple Notes

4

Uploaded by

kolagaming4927
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Tuple Notes

4

Uploaded by

kolagaming4927
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Q3. WAP to search for an element in a given list of numbers.

Ans.lst=eval(input(“Enter list:”))
length=len(lst)
element=int(input(“Enter element to be searched for:”))
for i in range(0,length):
if element==lst[i]:
print(element,”found at index”,i)
break
else:
print(element,”not found in given list”)

Q4. WAP to count the frequency of a given element in the list of numbers.
Ans . L=[2,58,95,999,65,32,15,1,7,45]
n=int(input("Enter the number : "))
print("The frequency of number ",n," is ",L.count(n))

Q5. Differentiate between append( ) and extend( ) functions.


Ans. The append() function/method adds a single item to the end of the existing list. It doesn’t return a
new list. Rather, it modifies the original list. The extend() adds all multiple items in the form of a list at the
end of another list.

TUPLES

A tuple is a collection which is ordered and immutable (We cannot change elements of a tuple in place).
Tuples are written with round brackets. Tuples are used to store multiple items in a single variable. Tuples
may have items with same value.
Exp. T = () # Empty Tuple
T = (1, 2, 3) # Tuple of integers
T = (1,3.4,7) # Tuple of numbers
T = (‘a’, ‘b’, ‘c’) # Tuple of characters
T = (‘A’,4.5,’Ram’,45) # Tuple of mixed values
T = (‘Amit’, ‘Ram’, ‘Shyam’) # Tuple of strings

Creating Tuples

A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
Exp. T = (10,20, ‘Computer’,30.5)

If there is only a single element in a tuple then the element should be followed by a comma, otherwise it will
be treated as integer instead of tuple. For example
T = (10) # Here (10) is treated as integer value, not a tuple
T1 = (10,) # It will create a tuple

73
Difference between List and Tuple

List Tuple
Elements are enclosed in square brackets i.e. [ ] Elements are enclosed in parenthesis i.e. ( )
It is mutable data type It is immutable data type
Iterating through a list is slower as compared to tuple Iterating through a tuple is faster as compared
to list

Accessing Elements of a tuple (Indexing)

Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing, for example
If str = (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’)

>>> str[2] = ‘M’


>>> str[-3] = ‘T’

Traversing a Tuple
Traversing a tuple means accessing and processing each element of it. The for loop makes it easy to
traverse or loop over the items in a tuple. For example:

str = (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’)


for x in str:
print(str[x])
The above loop will produce result as :
C
O
M
P
U
T
E
R
Tuple Operations
Concatenation (Joining Tuples)
The + operator is used to join (Concatenate) two tuples
Exp.
>>> T1 = (10,20,30)
>>> T2 = (11,22,33)
>>> T1 + T2
+ Operator concatenates Tuple T1 and Tuple T2 and creates a new Tuple
(10, 20, 30, 11, 22, 33)

74
Repetition
* Operator is used to replicate a tuple specified number of times, e.g.
>>> T = (10, 20, 30)
>>> T * 2
(10, 20, 30, 10, 20, 30)
Membership:
The ‘in’ operator checks the presence of element in tuple. If the element present it returns True, else it
returns False.
For Exp. str = (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’)
‘M’ in str => Returns True
‘S’ in str => Returns False

The not in operator returns True if the element is not present in the tuple, else it returns False.
‘M’ not in str => Returns False
‘S’ not in str => Returns True
Slicing
It is used to extract one or more elements from the tuple. Slicing can be used with tuples as it is used in
Strings and List. Following format is used for slicing:
S1 = T[start : stop : step]
The above statement will create a tuple slice namely S1 having elements of Tuple T on indexes start,
start+step, start+step+step, …, stop-1.
By default value of start is 0, value of stop is length of the tuple and step is 1
For Example:
>>> T = (10,20,30,40,50,60,70,80,90)
>>> T[2:7:3]
(30, 60)

>>> T[2:5]
(30, 40, 50)

>>> T[::3]
(10, 40, 70)

T[5::]
(60, 70, 80, 90)

Built-in functions/methods:
The len( ) function
This method returns length of the tuple or the number of elements in the tuple, i.e.,
>>> T = (10,20,30,40,50,60,70,80,90)
>>> len(T)
9

75
The max( ) function
This method returns element having maximum value, i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>>max(T)
600

>>> T = ('pankaj','pinki','parul')
>>> max(T)
'pinki'

The min( ) function


This method returns element having minimum value, i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>>min(T)
10

>>> T = ('pankaj','pinki','parul')
>>> min(T)
'pankaj'

The sum( ) function


This method is used to find the sum of elements of the tuple, i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>> sum(T)
990

The index( ) method


It returns the index of an existing element of a tuple., i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>> T.index(50)
4
But if the given item does not exist in tuple, it raises ValueError exception.
>>> T = (10,20,30,40,50,600,70,80,90)
>>> T.index(55)
ValueError: tuple.index(x): x not in tuple

The count( ) method


This method returns the count of a member / element (Number of occurrences) in a given tuple.,
i.e.,
>>> T = (10,20,30,20,20,0,70,30,20)
>>> T.count(20)
4

>>> T = (10,20,30,20,20,0,70,30,20)
>>> T.count(30)
2

76
The tuple( ) method
This function creates an empty tuple or creates a tuple if a sequence is passed as argument.
>>> L = [10, 20, 30] # List
>>> T = tuple(L) # Creates a tuple from the list
>>> print(T)
(10, 20, 30)

>>> str = "Computer" # String


>>> T = tuple(str) # Creates a tuple from the string
>>> print(T)
('C', 'o', 'm', 'p', 'u', 't', 'e', 'r')

The sorted( ) method


This function takes the name of the tuple as an argument and returns a new sorted list with sorted
elements in it.
>>> T = (10,40,30,78,65,98,23)
>>> X = sorted(T) # Make a list of values arranged in ascending order
>>> print(X)
[10, 23, 30, 40, 65, 78, 98]

>>> Y = sorted(T, reverse = False) # Make a list of values arranged in ascending order
>>> print(Y)
[10, 23, 30, 40, 65, 78, 98]

>>> Z = sorted(T, reverse = True) # Make a list of values arranged in descending order
>>> print(Z)
[98, 78, 65, 40, 30, 23, 10]

Tuple Assignment (Unpacking Tuple)

It 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.
Exp.
>>> T = ('A', 100, 20.5)
>>> x,y,z = T
>>> print(x,y,z)
A 100 20.5

Nested Tuple

A tuple containing another tuple in it as a member is called a nested tuple, e.g., the tuple shown below
is a nested tuple:
>>> students = (101,'Punit', (82,67,75,89,90)) # nested tuple
>>> len(students)
3

77
>>> print(students[1]) # 2nd element of tuple
Punit
>>> print(students[2]) # 3rd element of tuple
(82, 67, 75, 89, 90)
>>> print(students[2][3]) # Accessing 4th element of inner tuple
89

# Program to find sum of all the elements of a tuple


T = (10, 2, 30, 4, 8, 5, 45)
print(T)
s = sum(T)
print("Sum of elements : ", s)

Output
(10, 2, 30, 4, 8, 5, 45)
Sum of elements : 104

# Program to find minimum and maximum values in a tuple


T = (10,2,30,4,8,5,45)
print(T)
minimum = min(T)
maximum = max(T)
print("Minimum Value : ", minimum)
print("Minimum Value : ", maximum)

Output
(10, 2, 30, 4, 8, 5, 45)
Minimum Value : 2
Minimum Value : 45

# Program to find mean of values stored in a tuple


T = (10,2,30,4,8,5,46)
print("Tuple :", T)
s = sum(T)
NumberOfElements = len(T)
average = s/NumberOf Elements
print("Mean of elements : ", average)

Output
Tuple : (10, 2, 30, 4, 8, 5, 46)
Mean of elements : 15.0

78
# Write a program to find the given value in a tuple

T = (10,2,34,65,23,45,87,54)
print("Tuple :", T)
x = int(input("Enter value to search:"))
for a in T:
if a == x :
print("Value found")
break
else:
print("Value not found")
Output
Tuple : (10, 2, 34, 65, 23, 45, 87, 54)
Enter value to search:45
Value found

Q) Write a program to find sum of elements of tuple without using sum() function?
T = (10,20,30)
sum = 0
for x in T:
sum = sum + x
print(T)
print(sum)

Q) Write a program to find sum of even and odd elements of tuple


T = (10,23,30,65,70)
sumE = 0
sumO = 0
for x in T:
if (x%2 == 0):
sumE = sumE + x
else:
sumO = sumO + x
print(T)
print("sum of Even numbers :",sumE)
print("Sum of Odd Numbers : ", sumO)

79

You might also like