Unit 3 PPTs
Unit 3 PPTs
Unit 3 PPTs
user_function( )
Output—
Hello...Welcome Back
Types of Arguments
Function Arguments:
A function by using the following types of formal
arguments::
–Required arguments
–Keyword arguments
–Default arguments
–Variable-length arguments
Required arguments
def printme( str ):
"This prints a passed
string"
print (str)
return
printme(“python”)#calling
Keyword arguments:
• Keyword arguments are related to the function calls.
When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
• This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the
keywords provided to match the values with
parameters.
def printme( str ): "This prints a
passed string"
print str;
return;
printme( str = "My string");
• This would produce following result:
My string
Keyword arguments other example
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
Output: Name: miki Age 50
Rules:Positionalargument cannot
follow keyword argument
Printinfo(age=10,”john”) # error
#Positional argument follows keyword arguement
Printinfo(“john”,name=“john”)
#Duplicate value error
Variable-length arguments:
• An asterisk (*) is placed before the variable name that will hold the
values of all nonkeyword variable arguments. This tuple remains empty
if no additional arguments are specified during the function call. For
example:
def printinfo( arg1, *vartuple ):
"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
Return multiple values
def changeme( a ):
a=a+1
return a,3,4,5,6
m = 2;
print(m)
b=changeme( m );
print ("Values outside the function: ", b )
Recursion:
• A function is said to be def fact(n):
recursive if a statement
within the body of the if n==0:
function calls itself. return 1
• Suppose we want to find else:
the factorial then we can
apply recursion: return n*fact(n-1)
5!=5*4! Print(fact(5)) will give 120
=5*4*3!
=5*4*3*2!
=5*4*3*2*1
=120
Recursion
• Write a function calc_exp(base,exp) which
computes exponent of any function.
• A four digit number is entered through the
keyboard. Write a recursive function to
calculate the sum of four digits of the number
Solution-1
def find_exp(base,exp):
if exp==0:
return 1
else:
return base*find_exp(base,exp-1)
a=find_exp(13,2)
print(a)
Solution-2
def find_sum(number):
if number==0:
return 0
else:
return number%10+find_sum(number//10)
b=3533453
a=find_sum(b)
print("sum of digits of ",b,"is",a)
The Anonymous Functions:
• You can use the lambda keyword to create small
anonymous functions. These functions are called
anonymous because they are not declared in the standard
manner by using the def keyword.
• Lambda forms can take any number of arguments but
return just one value in the form of an expression. They
cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print
because lambda requires an expression.
• Although it appears that lambda's are a one-line version of
a function.
THE LAMBDA FUNCTION
• Also known as Anonymous Function (No name)
Syntax is:
Name = lambda(argument): expression
• Note—
1. It does not contain def keyword.
2. It does not contain return keyword.
3. It contains only one line statement but not block of
statement.
4. It cannot access global variable.
5. It is defined by lambda keyword.
6. It does not have any name. That why it is anonymous.
7. Multiple arguments are separated by commas.
Example—
Without lambda function
OUTPUT—
The sum is: 30 OUTPUT—
The sum is: 30
More Examples—
#
• Example—
Example— 1. def add(a,b,c):
• def add(a,b,c): 2. res=a+b-c
• res=a+b-c 3. return res
• return res 4. print(add(30,20,add(3,2,1))
• print(add(30,20,10)) )
OUTPUT— • OUTPUT—
• 40 • 46
A function in Python is called Higher Order Function,
if it contains at least one of the following:
Functions as objects :
1. def display(argument):
2. return argument.swapcase( )
Properties of higher order 3. print(display('CoRe PyThOn'))
function:
• 1) A function is an instance of # Assigning function to a variable
the Object type. 1. var = display
• 2) Function can be stored in a 2. print(var('CoRe PyThOn'))
variable. # to check references of display and
• 3) Function can be passed as a var
parameter to another 1. print(display)
function. 2. print(var)
• 4) Function can also be return • OUTPUT—
from a function. • cOrE pYtHoN
Passing FUNCTION as an Argument
Functions in Python are nothing but first class objects.
The functions can be passed as an argument to other
functions.
6. def identity(x):
7. return x
8. def square(x):
9. return x*x
10. def cube(x):
11. return x*x*x
12. print(sum(10,square))
13. #1+2+3...10
Map function
• In Python, map( ) function is used to apply a
function on all the elements of specified
iterable such as list, tuple etc. and return
modified list of items.
• Syntax of map( ) function is:
• Example—
• map(function, iterable, ...)
It returns a map object.
Example
1. def findSquare(n):
2. return n*n
3. num = (1, 2, 3, 4, 5)
4. answer = map(findSquare, num)
5. print(answer)
6. # converting map to list
7. FinalSquare = list(answer)
8. print(FinalSquare)
9. OUTPUT—
<map object at 0x03199E20>
[1, 4, 9, 16, 25]
Filter function
The filter( ) function is used to filter elements of an
iterable based on the function applied that tests
each element in the iterable to be true or false
Syntax of filter( ) function is—
filter(function, iterable)
Note:
1. The iterable can be a list, tuple, etc.
2. We can use only one iterable in filter( ) function.
Example— Let’s try to print even
numbers from 1 to 20
Method#1 Method#2
for value in range(1,21): result=list(filter(lambda value:
if value%2==0: value%2==0, range(1,21)))
print(value, end=" ") print(result)
OUTPUT— OUTPUT—
2 4 6 8 10 12 14 16 18 20 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
1. p = 20
2. def Demo():
3. q = 10
4. print("The value of Local Variable q: ", q)
5. print("The value of Global Variable p: ", p)
6. Demo()
7. print("The value of Global Variable p: ", p)
OUTPUT—
• The value of Local Variable q: 10
• The value of Global Variable p: 20
• The value of Global Variable p: 20
???
def f():
a=91
print(a)
a=10
print(a)
f()
print(a) 10,91,91 91,10,10 10,91,10
• 10
• 91
• 10
Global Variable
a=10
def f():
print(a)
f()
a=10
print(a)
f()
print(a)
• 10
• 10
• 10
• 10
11,10,10,10,10,11
a=11
def f():
print(a)
f()
a=10
f()
print(a)
f()
print(a)
a=11
f()
global key word
• a=11
• def f():
• global a
• a=a+1
• print(a)
• f()
• a=10
• f()
• print(a)
• f()
• print(a)
• a=11
• f()
• 11
• 10
• 10
• 10
• 10
• 11
Strings In Python
• A string represents a group of characters.
• In Python, the str datatype represents a string.
• Note: There is no separate datatype to
represent individual characters in Python
Strings are enclosed inside single quotes or
double quotes as:
• Str1 = ‘Welcome to Python Class’
• Str2 = “Welcome to Python Class”
Multiline Strings
• For multi-line strings, use triple single quotes or
triple double quotes.
• Examples:
• str = '''Welcome to Python Programming
class. Let's learn the concept
of Strings in Python.'''
• str="""Welcome to Python Programming
class. Let's learn the concept
of Strings in Python."""
Tabs and new lines
BASIC INBUILT PYTHON FUNCTIONS
FOR STRINGS
• len( ),min( ),max( )
• len( ) returns the number of characters in a string.
• min( ) returns smallest character present in a string.
• max( ) returns largest character present in a string.
NOTE: Max,Min always work on homogenous data
• Examples:
• >>> a = “PYTHON”
• >>> len(a)
6
• >>> min(a)
‘H’
• >>> max(a)
‘Y’
•
THE indexing [ ] Method
• Strings have
• Slicing Operators
• Slicing Operators with step size.
• + Operator
• * Operator
• in and not in Operator
The String Slicing Operator[start:end]
• The slicing operator returns a subset of string called slice by
specifying two indices i,e. start and stop.
• Syntax is—
• StringName[start: stop]
Example—
s = "KIET Delhi-NCR"
print(s[5:10])
Output—
Delhi
• NOTE:
• s[5:10] means that start index is 5 and stop one index less
than end parameter i,e. 10 – 1= 9
String Slicing with Step Size
Syntax is—
StringName[start: stop: step]
Example—
s= "KIET Delhi-NCR"
print(s[0:len(s):2])
Output:
KE eh-C
NOTE:
• If start and stop are not specified, the slicing is done from 0
to n-1.
• If step size is not specified, then it is taken as 1.
• Start and stop should be valid range to get the output.
Find the output Slicing
Find the Output—
str = "Core Python"
• print(str[0:9:1])
• print(str[0:9:2])
• print(str[::])
• print(str[2:4:1])
• print(str[::2])
• print(str[2::])
• print(str[:4:])
• print(str[-4:-1])
• print(str[-6::])
• print(str[-1:-4:-1])
• print(str[-1::-1])
Ans.
1. Core Pyth
2. Cr yh
3. Core Python
4. re
5. Cr yhn
6. re Python
7. Core
8. tho
9. Python
10. noh
11. nohtyP eroC
Repeating the Strings
Output—
Python ProgrammingPython Programming
• Example 2
• str="Core Python"
• print(str[5:7] * 2)
Output:
• PyPy
Concatenation of Strings
Example –
Output—
True
Example 2—
str2 = "Python Programming"
print("python" in str2)
Output—
False
Removing Spaces from a String
----------
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
• Other examples
• # integer arguments
• print("The number is:{:d}".format(123))
• # float arguments
• print("The float number is:{:f}".format(123.456789))
• # octal, binary and hexadecimal format print("bin:
{0:b}, oct: {0:o}, hex: {0:x}".format(12))
Comparing Strings
•
The relational operators such as >, >=, <, <=, ==, != operators to compare two strings.
They return True or False depending on the strings being compared.
Example 1—
str1 = "Box"
str2 = "Boy"
if str1 == str2:
print("Both are same")
else:
print("Not same")
Output—
Not same
Example 2—
str1 = "Box"
str2 = "Boy"
if str1 < str2:
print("str1 is less than str2")
else:
print("str1 is greater than or equal to str2")
Output—
str1 is less than str2
• Example 3—
• str1 = "abcd"
• str2 = "ABCD"
• print(str1 > str2)
•
• Output—
• True
•
• Example 4—
• str1 = "ABC"
• str2 = "DEF"
• print(str1 > str2)
•
• Output—
• False
•
•
String Functions
str = "welcome to python programming"
print(str.capitalize( ))
Makes only first character capital rest all small
print(str.title( ))
Makes only first character of each word capital rest all small
Output—
Welcome to python programming
Welcome To Python Programming
Str.lower()
• Examples—
• str = "PYTHON"
• print(str.lower( ))
•
• Output—
• Python
Str.upper()
• Examples—
• str = "python"
• print(str.upper( ))
•
• Output—
• PYTHON
Str.swapcase
• Examples—
•
• str="IncreDible India"
• print(str.swapcase( ))
•
• Output—
• iNCREdIBLE iNDIA
•
Str.replace
Example—
str1="I have brought two chocolate, two cookies
and two cakes"
str2=str1.replace("two","three")
print(str2)
Output—
I have brought three chocolate, three cookies and
three cakes
Str.replace() with count parameter
Example—
str1="I have brought two chocolate, two cookies
and two cakes"
str2=str1.replace("two","three",2)
print(str2)
Output—
I have brought three chocolate, three cookies and
two cakes
Str.count()
Examples—
str1="Python Programming"
str2=str1.count("n")
print(str2)
Output—
2
Str.endswith()
Examples—
str1="www.kiet.edu"
str2=str1.endswith("edu")
print(str2)
Output—
True
Str.startwith()
Examples—
str1="www.kiet.edu"
str2=str1.startswith("w")
print(str2)
Output—
True
Finding Sub Strings
Output—
8
str.find()
• Examples—
• str1="Python Programming"
• str2=str1.find("Programming")
• print(str2)
•
•
• Output—
• 7
•
str.rfind()
• Examples—
• str1="Python Programming"
• str2=str1.rfind("n")
• print(str2)
•
• Output—
• 16
Examples—
str1="Python Programming"
str2=str1.find("b")
print(str2)
Output—
-1
str.split()
Examples—
str1="Python Programming"
str2=str1.split()
print(str2)
Output—
['Python', 'Programming']
str.split() with parameter
Examples—
str1="Python Programming"
str2=str1.split("on")
print(str2)
Output—
['Pyth', ' Programming']
str.split() other examples
• Examples—
• str1="one,two,three,four"
• str2=str1.split(",")
• print(str2)
•
• Output—
• ['one', 'two', 'three', 'four’]
• Give output: “pythonnn”.split(“n”)
Str.join() Join all items in a sequence
data into string, using a a separator:
• Examples—
• str1=["one","two","three“]
• str2="-".join(str1)
• print(str2)
•
• Output—
• one-two-three
str.join() example
• Examples—
• str1=["apple","guava","grapes","mango"]
• sep=":"
• str2=sep.join(str1)
• print(str2)
•
• Output—
• ‘apple:guava:grapes:mango’
Examples—
str1="Python Programming"
str2=str1.find("min")
print(str2)
Output—
14
str1="Python Programming"
str2=str1.find("n")
print(str2)
Output—
5
Summary of string functions
1. capitalize( )
2. lower( )
3. upper( )
4. title( )
5. swapcase( )
6. replace(old,new)
7. count(str)
8. endswith(str)
9. startswith(str)
10. split( )
11. join(str)
12. find(str)
13. rfind(str)
Give Output
Compare the output of following python
Expressions
1. print(eval (“42+2”))
2. print("42+2")
3. print(int("42+2“))
4. print(“42”+”2”)
Question-1
1. Assume the variable named n holds a
positive integer value. How do you determine
the last digit of n?
Write solution on
Laptop/Mobile/Notebook and share
on group
Read current date time from the user in the
format as a string
“DD-MM-YYYY HH:MM:SS”
s1 = "spam"
s2 = "ni!"
• show a Python expression that could
construct each of the following results by performing
string operations on s1 and s2.
(a) ‘span’
(b) [ ‘sp’ , ’m’]
(c) ‘spm’
Solution
Quiz Question
• Given the initial statements:
s1 = "spam"
s2 = "ni!"
Show the result of evaluating each of the following
string expressions.
(a) s1[1:3]
(b) s1[2] + s2[:2]
(c) s1 + s2[-1]
Solution
Quiz Question
• Given the initial statements:
s1 = "spam"
s2 = "ni!"
Show the result of evaluating each of the following
string expressions.
(a) 3 * s1 + 2 * s2
(b) s1[1]
Quiz-Question
• Write a program that takes a sentence of at least 20
characters as input and returns a new string
replacing each vowel with its case changed.
Solution
Lists
Lists in Python:
• In python, A list is sequence of values called items or elements. The
elements can be any type..
• A sequence is an object that holds multiple items of data, stored one after
the other.
• So A list is a sequence object that contains multiple data items.
• We use square bracket[ ] to represent a list.
Properties:
1. Lists are mutable, which means that their contents can be changed
during a program’s execution
2. Lists are dynamic data structures, meaning that items may be added to
them or removed from them
3. You can use indexing, slicing, and various methods to work with lists in a
program.
Creating List
• A list Class defines lists. A programmer can use a list’s
Constructor to create list or [] syntax.
a. Create a empty list
L1=list(); or L1=[]
b. Create a list with any three integer elements
L2= list([10,20,30]) or L2= [10,20,30]
c. Create a list with three string elements
L3 = list( [“Apple” , ”banana” , ”grapes” ]) or
L3= [ “Apple” , ”banana” , ”grapes” ]
d. Create a list using inbuilt range function
L4=list(range(0,6))
e. Create a list using character of string
L5= list(“xyz”)
Python - Lists
• The list is a most versatile data type available in Python, which can be
written as a list of comma-separated values (items) between square
brackets.
• Good thing about a list that items in a list need not all have the same
type:
• Creating a list is as simple as putting different comma-separated values of
different types. For example:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
Accessing Values in Lists:
• To access values in lists, use the square brackets for slicing
along with the index or indices to obtain value available at
that index:
• Example:
list1 = ['physics', 'chemistry', 1997,
2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
• This will produce following result:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Negative List Indices
The negative Index access the elements from the
end of a list counting in backward direction. The
index of the last element of any non empty list is
always -1.
>>>list1=[10,20,30,40,50,60]
>>>list1[-1] will give 60
>>>list1[-2] will give 50
>>>list1[-3] will give 40 and so on upto
>>> list1[-6] will give 10
A Quick Question?
• numbers = list(range(1, 10, 2))
Quick Answer:?
List Slicing
A slicing expression selects a range of elements from a sequences
• A slice is a span of items that are taken from a sequence. When you
take a slice from a list, you get a span of elements from within the
list.
• To get a slice of a list, you write an expression in the following
general format:
list_name[start : end]
• In the general format, start is the index of the first element in the
slice, and end is the index marking the end of the slice.
• The expression returns a list containing a copy of the elements
from start up to (but not including) end.
• days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday']
• mid_days = days[2:5]
['Tuesday', 'Wednesday', 'Thursday']
Slicing examples
• If numbers = [1, 2, 3, 4, 5]
• 2>>> print(numbers) [1, 2, 3, 4, 5]
• >>> print(numbers[2:]) [3, 4, 5]
• >>> print(numbers[:]) [1, 2, 3, 4, 5]
• If numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• >>> print(numbers[1:8:2]) [2, 4, 6, 8]
• >>> print(numbers[-5:])[6, 7, 8, 9, 10]
Slicing:
• Because lists are sequences, indexing and slicing work the same way for lists as they
do for strings.
• Assuming following input:
L = ['spam', 'Spam', 'SPAM!']
• print(FindList[::-1])
• print(FindList[-1:0:-1])
• OUTPUT—
• [10, 20, 30]
• >>>a=[2, 56]
• >>> b=["anj","d"]
• >>> a+b
• [2, 56, 'anj', 'd']
•
Membership test
• in operations can be applied to test the
whether an element is part of list or not.
Or we can use
List2=list1[:]
PYTHON INBUILT FUNCTIONS FOR
LISTS
• len( )—returns number of items in the list
• max( )—return item with maximum value
• min( )—return item with minimum value
• sum( )—return sum of all items in the list
• random.shuffle( )—shuffle items randomly
Examples
MyList=[10,20,30,40,50]
print(MyList)
print(len(MyList))
print(max(MyList))
print(min(MyList))
print(sum(MyList))
import random
random.shuffle(MyList) # will the shuffle in the original list
print(MyList)
OUTPUT—
[10, 20, 30, 40, 50]
5
50
10
150
[40, 30, 20, 50, 10]
What if we want original list and shuffle list also.
Solution
list1 = list(range(5))
print(list1)
import random
list1_new = random.sample(list1, len(list1))
print(list1_new)
OUTPUT—
[0, 1, 2, 3, 4]
[1, 4, 3, 2, 0]
List Methods in python
Lists have numerous methods that allow you to work with the
elements that they contain. Python provides built-in functions
that are useful for working with lists.
OUTPUT—
['apple', 'banana', 'cherry', 'orange']
Example : Append()
insert( ) method
• This method adds an item Before the specified index of the list. The
insert method allows you to insert an item into a list at a specific
position.
• You pass two arguments to the insert method: an index specifying
where the item should be inserted and the item that you want to
insert
OUTPUT—
['apple', 'banana', 'orange', 'cherry']
The remove Method
list1.extend(list2)
print(list1)
OUTPUT—
MyList = ['A','B','C','A','B','C']
print(MyList.count('A'))
OUTPUT—
2
Index method
• Earlier you saw how the ‘in operator’ can be
used to determine whether an item is in a list.
• Sometimes you need to know not only
whether an item is in a list, but where it is
located. The index method is useful in these
cases. You pass an argument to the index
method and
• it returns the index of the first element in the
list containing that item. If the item is not
found in the list, the method raises a Value
Error exception.
Example program: index
reverse( ) method
MyList = ['A','B','C','D','E','F']
MyList.reverse( )
print(MyList)
OUTPUT—
MyList = ['D','B','A','F','E','C']
MyList.sort(reverse=True)
print(MyList)
OUTPUT—
['F', 'E', 'D', 'C', 'B', 'A']
How to convert String to List of
Characters
str="Python"
print(str)
MyList=list(str)
print(MyList)
Output—
Python
['P', 'y', 't', 'h', 'o', 'n']
Here the list( ) function breaks a string into individual
letters.
Question
• Consider the list. Write a Python program to
retrieve only the first letter of each word from
the given list.
• words=['Apple','Banana','Orange','Cherry']
Solution
• words=['Apple','Banana','Orange','Cherry']
• MyList=[ ]
• for w in words:
• MyList.append(w[0])
• print(MyList)
•
• OUTPUT—
• ['A', 'B', 'O', 'C']
Checkpoint questions
• del vs remove method?
• if My_list[mid]==key:
• return mid
• elif key>My_list[mid]:
• low=mid+1
• else:
• high=mid-1
• return -1
• My_list=[10,20,56,516,3576,34324,3245213]
• result=binary_search(My_list,34324)
• if(result!=-1):
• print("Element found at position",result)
• else:
• print("Element not found")
List Comprehensions
List comprehensions represent creation of new lists from
an iterable object(such as list, set, tuple, dictionary)
that satisfy a given condition.
OR
Squares=[i**2 for i in range(1,101)]
Print(square)
……………………………………………………………
d=[i*3 for i in range(23) if i%2==0]
Questions on Comprehensions
• Q1. Create a list having numbers
[1,4,7,10,.....100] as its elements using list
comprehension method.
• Q2. WAP to generate a list of 10 starting
multiple of 5 using list comprehension method
• 3
num_list = [x for x in range(100) if x % 10 == 0]
print(num_list)
• OR a=[i*10 for i in range(0,10)]
Other Examples
num = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(num)
Output:
Example—
Tup1=tuple("PYTHON")
print(Tup1)
OUTPUT—
('P', 'Y', 'T', 'H', 'O', 'N')
Example—
Tup2=tuple([1,2,3])
print(Tup2)
OUTPUT—
(1, 2, 3)
FUNCTIONS FOR TUPLE
1. len( )
2. max( )
3. min( )
4. sum( )
index( )
count( )
Example—
codes Output
Tup1=(1,2,3,3,4,5,2) OUTPUT—
1. print(Tup1) 1. (1, 2, 3, 3, 4, 5, 2)
2. print(len(Tup1)) 2. 7
3. print(max(Tup1)) 3. 5
4. print(min(Tup1)) 4. 1
5. print(Tup1.index(2)) 5. 1
6. print(Tup1.count(3)) 6. 2
Tuple Examples
Tup2=tuple("CORE PYTHON") OUTPUT—
1. print(Tup2) 1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y',
2. print(len(Tup2)) 'T', 'H', 'O', 'N')
3. print(max(Tup2)) 2. 11
4. print(min(Tup2)) 3. Y
5. print(Tup2.index('H')) 4.
6. print(Tup2.count('O')) 5. 8
6. 2
INDEXING & SLICING IN TUPLE
• + Operator
• * Operator
•
The + Operator
It is the concatenation operator that is used to join two tuples.
Example—
Tup1=(1,2,3)
Tup2=(4,5,6)
Tup3=Tup1 + Tup2
print(Tup3)
OUTPUT—
(1, 2, 3, 4, 5, 6)
The * Operator
Example—
Tup=(1,2,3)
Tup2=Tup * 2
print(Tup2)
OUTPUT—
(1, 2, 3, 1, 2, 3)
How to sort elements in Tuple
Method1—
Convert given tuple to list and then apply sort( ) method.
Example—
Tup=(1,4,2,5,3)
print(Tup)
List1=list(Tup)
List1.sort()
Tup1=tuple(List1)
print(Tup1)
OUTPUT—
(1, 4, 2, 5, 3)
(1, 2, 3, 4, 5)
Method2—
Example:
Tup=(1,4,2,5,3)
print(sorted(Tup))
OUTPUT—
[1, 2, 3, 4, 5]
Sorting Examples
Example:
Tup=tuple("PYTHON")
print(sorted(Tup))
OUTPUT—
['H', 'N', 'O', 'P', 'T', 'Y']
Example—
Tup=tuple("PYTHON")
print(sorted(Tup,reverse=True))
OUTPUT—
['Y', 'T', 'P', 'O', 'N', 'H']
Deleting a Tuple
print(Tup_new)
Tup_new = ('p','y','t','h','o','n') # NameError: name 'my_tuple'
print(Tup_new) is not defined
>>> Grades={"Tammana":"A","Pranav":"B","Sumit":"C"}
>>> for key in Grades:
print(key,":",str(Grades[key]))
Tammana : A
Sumit : C
Pranav : B
Nested Dictionaries
Traversing Nested Dictionaries
Sorting Dictionary
• You can obtain a sorted list of the keys using
the sorted() function.
>>>prices = {'Apple': 1.99, 'Banana': 0.99, 'Orange':
1.49, 'Cantaloupe': 3.99, 'Grapes': 0.39}
>>>sorted(prices)
['Apple', 'Banana', 'Cantaloupe', 'Grapes', 'Orange']
Note that
my_dict = {4:'e', 3: 'd', 2: 'c', 1: 'b', 0: 'a'}
print(my_dict) Indexing is not applicable in
print(my_dict[0]) dictionary. Here 0, 4 represent
print(my_dict[4]) the key 0 and key 4
respectively.
#print(my_dict[-1])
#print(my_dict[0:2]) Slicing is also not applicable in
dictionary.
OUTPUT— Therefore,
{4: 'e', 3: 'd', 2: 'c', 1: 'b', 0: 'a'} print(my_dict[-1]) gives KeyError:
a -1
e
print(my_dict[0:2]) gives
• TypeError: unhashable type:
'slice'
Q1 Find the output?
1. 30
2. None
3. -1
my_dict = {'a': 10, 'b': 20, 'c': 30}
1. print(my_dict.pop('b'))
2. print(my_dict.pop('z'))
3. print(my_dict.pop('z', -1))
4. print(my_dict)
ans
1. 20
2. Key Error
3. -1
4. {'a': 10, 'c': 30}
• Que Write a Python program to sum all values
of the items in a dictionary.
• my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
OUTPUT—
293
SETS IN PYTHON
Note: A set cannot have a mutable element, like list, set or dictionary, as its
element.
Example—
set1 = {1, 2, 3, 4, 5}
print(set1)
OUTPUT—
{1, 2, 3, 4, 5}
{'Python', (1, 2, 3, 4, 5), 5}
Example
set3 = {1, 2, 3, 4, 5, 3, 2, 5}
print(set3)
Output—
{1, 2, 3, 4, 5}
Example—
OUTPUT—
TypeError: unhashable type: 'list'
Example—
OUTPUT—
Type Error: unhashable type: 'set'
Example—
My_list=[1,2,3,4,5]
print(My_list)
My_set=set(My_list)
print(My_set)
OUTPUT—
[1, 2, 3, 4, 5]
{1, 2, 3, 4, 5}
Example—
My_tuple=(1,2,3,4,5)
print(My_tuple)
My_set=set(My_tuple)
print(My_set)
OUTPUT—
(1, 2, 3, 4, 5)
{1, 2, 3, 4, 5}
METHODS IN SETS
• add( )
• remove( )
• clear( )
• issubset( )
• issuperset( )
• union( )
• intersection( )
• difference( )
• symmetric_difference( )
add( element)
Add the element into the set.
Example—
set1={1,2,3,4,5}
print(set1)
set1.add(10)
print(set1)
OUTPUT—
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 10}
remove(element) / discard(element)
Example—
set2={1,2,3,4,5}
print(set2)
OUTPUT—
{1, 2, 3, 4, 5}
{1, 2, 4, 5}
issubset( setName)
OUTPUT—
True
clear( )
Remove all elements from the set.
Example—
set3={1,2,3,4,5}
print(set3)
set3.clear()
print(set3)
OUTPUT—
{1, 2, 3, 4, 5}
set()
issuperset( setName)
1. s1={10,20,30,40}
2. s2={10,20,30,40,50}
3. print(s2.issuperset(s1))
OUTPUT—
True
SET OPERATIONS
• union( )
• intersection( )
• difference( )
• symmetric_difference( )
union( ) method
The union of two sets S1 and S2 is a set of elements that are
present in S1 or in S2 or in both S1 and S2.
Syntax is:
1. set1.union(set2)
Symbol is:| i.e, vertical bar
Example—
s1={10,20,30}
s2={10,20,30,40,50}
print(s1.union(s2))
OUTPUT—
• {40, 10, 50, 20, 30}
Example—
1. s1={10,20,30}
2. s2={10,20,30,40,50}
3. s3=s1 | s2
4. print(s3)
OUTPUT—
{40, 10, 50, 20, 30}
intersection( ) method
OUTPUT—
• {10, 20, 30}
difference( ) method
Syntax is:
set1.difference(set2)
Symbol is: -
s1={10,20,30,40,50}
s2={30,40,50,60,70}
print(s1.difference(s2))
OUTPUT—
{10, 20}
s1={10,20,30,40,50}
s2={30,40,50,60,70}
s3=s1 - s2
print(s3)# will remove common element from s1
Symmetric_difference( ) method
OUTPUT—
{20, 70, 10, 60}
'difference_update',
• >>> a={3,4,5}
• >>> b={3,4,534,4}
• >>> a-b
• {5}
• >>> a
• {3, 4, 5}
• >>> b
• {3, 4, 534}
• >>> a.difference_update(b)
• >>> a
• {5}
• >>> b
• {3, 4, 534}
• >>>
NOTE:
We cannot access items in a set by referring to an index,
since sets are unordered the elements has no index.
But we can check if a specified element is present in a set
or not, by using the in keyword.
Example—
Myset = {"dell", "sony", "lenovo", "hp"}
print("lenovo" in Myset)
OUTPUT—
True
How to change elements in Set
•
Once a set is created, we cannot change its elements, but we can
add new elements.
Add Elements in Set
To add one element to a set use the add( ) method.
To add more than one element to a set use the update( ) method.
Example—
OUTPUT—
{'lenovo', 'sony', 'dell', 'hp', 'samsung'}
Example— Update
OUTPUT—
{'apple', 'samsung', 'sony', 'dell', 'hp', 'lenovo'}
Display unique string along with length
formed by alphabetical sorting of
unique symbols
• E.g. if input is ppyythonn
• Then output should be: hnopty6
Solution
• unique=set(input())
• l=list(unique)
• l.sort()
• d=""
• for i in l:
• d+=i
• print(d+str(len(d)))