Nothing Special   »   [go: up one dir, main page]

Unit 3 PPTs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 275

FUNCTIONS

• Python has built-in functions as well as User-defined


functions.
• Examples of built-in functions
• print( ), input( ), type( ) etc.
• Now we will discuss in detail User-defined function in
Python.
• In Python, a function is a group of statements that are used
to perform a specific task.

• Functions help to break our program into smaller modules
and make our program more organized, readable.
Some advantages of functions:

• Complex codes can be divided into smaller parts.


• Once function is written, it can be reused as and when required.
This helps programmer to avoid writing the same code again and
again.
• Functions provide modularity in a code.
• Code maintenance becomes very easy. To add any new feature in
the code, just create new functions and if the user does not want
any specific feature, that can be removed from the code.
• When there is an error in the software, the corresponding function
can be modified without disturbing any other functions in the
software. This makes code debugging will become easy.
• The use of functions in a program will reduce the length of the
program
Defining a Function
• Syntax is
• def functionName(p1, p2, …):
• statement1
• statement2

• Note—
• def is the keyword
• Use of parenthesis i.e,( ) after function name.
• p1, p2, .. are the parameters
• Colon(:) sign at the end of the function name.
• Example—
• def user_function( ):
print("Hello...Welcome Back")
Calling an function

• To call a function in our code, use the function name


followed by parenthesis:
Example
def user_function( ):
print("Hello...Welcome Back")

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

Find cube a number n, where n = 3.


def fun(n):
return n**3
print("The cube of 3 is:",fun(3))
OUTPUT—
The cube of 3 is: 27

With lambda function


cube = lambda n: n**3
• print("The cube of 3 is:",cube(3))
More Examples—
# sum of two numbers

Without lambda function With lambda function


1. def sum(x,y):
2. return x+y 1. sum = lambda x,y: x+y
3. print("The sum 2. print("The sum
is:",sum(10,20)) is:",sum(10,20))

OUTPUT—
The sum is: 30 OUTPUT—
The sum is: 30
More Examples—
#

Without Lambda With lambda function


1. def max(x,y):
2. if x > y:
1. max = lambda x,y: x if x>y
3. return x else y
4. else: 2. print("The maximum of
5. return y 10,20 is:",max(10,20))
6. print("The maximum of 10,20
is:",max(10,20))
OUTPUT—
OUTPUT— The maximum of 10,20 is: 20
The maximum of 10,20 is: 20
Example:
• Following is the example to show how lembda form of function works:
sum = lambda arg1, arg2: arg1 + arg2;
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ) )
• This would produce following result:
Value of total : 30
Value of total : 40
Higher Order Function

ctions A function can be returned as a


A function can take one or more
functions as arguments result of another function

• 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.

1. def display(argument): 8. welcome(display)


2. return argument.capitalize( ) 9. welcome(show )
3. def show(argument):
Hello guys, welcome back
4. return argument.title( )
5. def welcome(function): Hello Guys, Welcome Back
6. # storing the function in a
variable
7. msg = function("hello guys,
welcome back")
print(msg)
Using Functions as Object
• We cannot differentiate between data and functions in
python
• Because functions can be passed as arguments
• Even we can return functions
• We can also make functions as member of sequence
data structure.
Try to solve the problem: Write a function sum with two
parameters find sum of either squares/cubes/single
powers for first n given numbers depending on
following parameters:
e.g. Sum(n, function) n=Number of terms:
function: Parameter to hold function name
of other function for finding
square/cube/identity
Demo Example
1. def sum(n,fun):
2. s=0
3. for i in range(1,n+1):
4. s=s+fun(i)
5. return s

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]

Only one iterable we can use in


filter.
Example

1. characters = ['c', 'o', 'r', 'e', 8. get_filtered_Vowels =


'p', 'y', 't', 'h', 'o', 'n'] filter(My_Vowels, characters)
2. def My_Vowels(characters): 9. print('The filtered vowels from
3. vowels = ['a', 'e', characters are:')
'i', 'o', 'u'] 10. for ch in get_filtered_Vowels:
4. if(characters in print(ch)
vowels): output
5. return True • o
6. else: • e
7. return False • o
Reduce function
• The reduce( ) function is used to apply a function to
all of the elements of the iterable.
• It returns a single value as an output.
• This function is defined in “functools” module
• Syntax—
reduce(function, iterable)
• The argument function is applied cumulatively to
arguments in the list from left to right.
• The result of the function in the first call becomes the
first argument and the third item in list becomes
second. This is repeated until the list is exhausted.
Example—

# to add all numbers of a list


1. from functools import reduce
2. def sum(a, b):
3. return a + b
4. print(reduce(sum, [1, 2, 3, 4, 5]))
OUTPUT—
15
SCOPE Rules
Local Variables
• A local variable is created inside a function and cannot be
accessed by statements that are outside the function.
• Different functions can have local variables with the same names
because the functions cannot see each other’s local variables.

• Anytime you assign a value to a variable inside a function, you


create a local variable.

• A local variable belongs to the function in which it is created, and


only statements inside that function can access the variable.

• An error will occur if a statement in one function tries to access a


local variable that belongs to another function.
THE LOCAL AND GLOBAL SCOPE OF A VARIABLE
• Variables and parameters that are initialized within a function including
parameters are said to be exist in that function’s local scope.

• Variables that exist in local scope are called local variables.


• Variables that exist in global scope are called global variables.

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

• The characters in a string can be accessed one


at a time through the index operator.
• The string indexing starts from 0.
Example
str =“PYTHONPROGRAMMING”
print(str[0])
print(str[-1])
Output:
P
G
• If we write print(str[16]), Python will through an
error i,e.
• IndexError: string index out of range
THE STRING OPERATORS

• 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

The repetition operator is *


It is used to repeat the string for several times.
Syntax is—
str * n repeats the string for n times.
Example 1
str = "Python Programming"
print(str * 2)

Output—
Python ProgrammingPython Programming
• Example 2
• str="Core Python"
• print(str[5:7] * 2)
Output:
• PyPy
Concatenation of Strings

The concatenation operator for strings in Python is +

Example –

str1 = "Python "


str2 = "Programming"

str3 = str1 + str2


print(str3)
Output—
Python Programming
Checking Membership

in and not in operator


• We can check if a string or character is a member of
another string or not.

• The ‘in’ operator returns True if the string or character is


found in the main string.

• It returns False if the string or character is not found in the


main string.

• The ‘not in’ operator returns False if a string or character is


not found in the main string otherwise True.
Example
Example 1—
str1 = "Python Programming"
print("Python" in str1)

Output—
True

Example 2—
str2 = "Python Programming"
print("python" in str2)

Output—
False
Removing Spaces from a String

• A space is also considered as a character inside a


string.
• Sometimes, it’s necessary to remove such spaces
from the string to get correct result.

• Example—
• if "Python " == "Python":
• print("Both are same")
• else:
• print("Both are NOT same")
Stripping white spaces in strings
Note that these methods do not remove spaces which are in the
middle of the string.
Other Examples
• Examples—
• >>> str1 = "\t\t Hey, How are you\t\t"
• >>> str1
• '\t\t Hey, How are you\t\t'
• >>> str1.lstrip()
• 'Hey, How are you\t\t'
• >>> str1.rstrip()
• '\t\t Hey, How are you'
• >>> str1.strip()
• 'Hey, How are you'
Removing other than space
• Example—
• >>> str1 = "@Cost of this pen is Rs = 20###"
• >>> str1
• '@Cost of this pen is Rs = 20###'
• >>> str1.strip("@#")
• 'Cost of this pen is Rs = 20'
Str.format()
• str.format() is one of the string formatting methods in
Python3, which allows multiple substitutions and value
formatting.
• Syntax: “{ }” .format(value)
• {}: placeholders in string, and could by any in number but
equal to or greater thant number of values
• Value: is any string,int,or float variable to substituted.
• Placeholder indexing by default starts from 0,1 ..
If not initialized.
Other formatting options in str.format
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for
{2:.2f} dollars."
print(myorder.format(quantity, itemno, price))

----------
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

• The find( ) and rfind( ) methods are useful to locate substring in a


string.

• These methods return the location of the first occurrence of the


substring in the main string.
• The find( ) methods search for the substring from the beginning of
the main string.
• The rfind( ) methods search for the substring from right to left.

• These method returns -1 if the substring is not found in the main


string.
Str.find()
Examples—
str1="Python Programming"
str2=str1.find("r")
print(str2)

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”

Extract all values sep. and print seprately using


string formatting as
“Today is DD day of MM month in the year YYYY
and current time is HH hours MM minutes and
SS seconds”
st="30-04-2021 04:05:55“
• Write function To get a string made of the first
2 even and the last 2 chars from a given a
string. If the string length is less than 2, display
empty string
Solution
string=input("Enter string of your choice")
if(len(string)<2):
print("NULL");
else:
print(string[0:2]+string[-2::]);
Quiz Question:
• Given the initial statements:

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!']

Python Expression Results Description


L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from


the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Checkpoint
• What will the following code display?
numbers = [1, 2, 3, 4, 5]
my_list = numbers[:1]
print(my_list)
Try to answer
FindList=[10,20,30,40,50]
• print(FindList[:3])

• print(FindList[::-1])
• print(FindList[-1:0:-1])
• OUTPUT—
• [10, 20, 30]

• [50, 40, 30, 20, 10]


• [50, 40, 30, 20]
Repetition
• Repetition
The * symbol multiplies two numbers. However, when the
operand on the left side of the * symbol is a sequence (such
as a list) and the operand on the right side is an integer, it
becomes the repetition operator.

• >>> numbers = [0] * 5


• >>> print(numbers)
[0, 0, 0, 0, 0]
Question?
l1=list(“InfyTq”)
then

>>> l1*3 will be


Delete List Elements:
• To remove a list element, you can use either the del
statement if you know exactly which element(s) you are
deleting or the remove() method if you do not know.
Remove method will ask for value to be deleted.
• Example:
list1 = ['physics', 'chemistry', 1997,
2000];
del list1[2];
print ("After deleting index 2 : “)
print (list1)
• This will produce following result:
After deleting value at index 2 :
['physics', 'chemistry', 2000]
>>>list1.remove('physics')
>>> list1
['chemistry', 2000]
Del Examples
• Example—
• >>> MyList=[10,20,30,40,50,60]
• >>> MyList
• [10, 20, 30, 40, 50, 60]
• >>> del MyList[1]
• >>> MyList
• [10, 30, 40, 50, 60]
• >>> del MyList[-1]
• >>> MyList
• [10, 30, 40, 50]
• >>> del MyList[1:3]
• >>> MyList
• [10, 50]
Finding length of List
• Python has a built-in function named len that returns the
length of a sequence, such as a
list. The following code demonstrates:
my_list = [10, 20, 30, 40]
size = len(my_list)
print(size) will give 4
• The first statement assigns the list [10, 20, 30, 40] to the
my_list variable.
• The second statement calls the len function, passing the
my_list variable as an argument
+ will act as concatenation for List as
well

• >>>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.

>>> 'Sanjeev' in ['sonu', 'rajiv', 'Sanjeev']


True
>>>
Basic List Operations: SUMMARY
• Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.
• In fact, lists respond to all of the general sequence operations we used on strings
in the prior 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, 123 Iteration


Write a python program to read sales
of five days in list using loop
• A=[]
• For i in range(5):
A[i]= int(Input(“Enter the sale”))
Write a python program to read sales
of five days in list using loop
• sales = [0] * NUM_DAYS
• index = 0
• print('Enter the sales for each day.')
• while index < NUM_DAYS:
• print('Day #', index + 1, ': ', sep='', end='')
• sales[index] = float(input())
• index += 1
• print('Here are the values you entered:')
• for value in sales:
• print(value)
Expected output
Checkpoint Question
• What will the following code display?
numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]
numbers2 += numbers1
print(numbers1)
print(numbers2)
List of Strings can be concatenated through + or += operations
with other string but not number list with string

In this case each character of string becomes member in


combined list
Copying list
Recall that in Python, assigning one variable to
another variable simply makes both variables
reference the same object in memory.
• For example, look at the following code:
• list1 = [1, 2, 3, 4]
• list2 = list1
• After this code executes, both variables list1
and list2 will reference the same list in
memory.
Copied Lists refers to same object
• To demonstrate this,
• >>> list1 = [1, 2, 3, 4]
• >>> list2 = list1
• >>> print(list1)
• [1, 2, 3, 4]
• >>> print(list2)
• [1, 2, 3, 4]
• >>> list1[0] = 99
• >>> print(list1)
• [99, 2, 3, 4]
• >>> print(list2)
• ?????????
Creating different but identical lists
• Suppose you wish to make a copy of the list, so that list1
and list2 reference two separate but identical lists.
• One way to do this is with a loop that copies each element
of the list. Here is an example:
• # Create a list with values.
• list1 = [1, 2, 3, 4]
• # Create an empty list.
• list2 = []
• # Copy the elements of list1 to list2.
• for item in list1:
• list2.append(item)
OR we can use :
• list1 = [1, 2, 3, 4]
• list2 = [] + list1
Using built in methods
• List1=[“red”,”blue”,”pink”]
• List2=List1.copy() # will copy list1 to list2
>>>list2 will give [“red”,”blue”,”pink”]

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.

• The append Method


The append method is commonly used to add items to a list. The
item that is passed as an argument is appended to the end of the
list’s existing elements.
List.append()
This method adds an item to the end of the list.
MyList = ["apple", "banana", "cherry"]
MyList.append("orange")
print(MyList)

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

MyList = ["apple", "banana", "cherry"]


MyList.insert(2, "orange")
print(MyList)

OUTPUT—
['apple', 'banana', 'orange', 'cherry']
The remove Method

• The remove method removes an item from the


list.
• You pass an item to the method as an argument
and the first element containing that item is
removed.
• This reduces the size of the list by one element.
• All of the elements after the removed element
are shifted one position toward the beginning of
the list.
• A Value Error exception is raised if the item is not
found in the list.
Example: Remove method
• list1 = ['P’, 'B', 'C']
• print('Here are the items in the food list:')
• print(list1)
• item = input('Which item should I remove? ‘)
• list1.remove(item)
• print('Here is the revised list:')
• print(list1)
Here are the items in the food list:
• ['P', 'B', 'C']
• Which item should I remove? B
• Here is the revised list:
• ['P', 'C']
pop( ) method #with or without
parameter
• This method removes the specified index from the list.
• If index is not specified, then it removes the last item
from the list.

• MyList = ['apple', 'banana', 'cherry']
• MyList.pop( )
• print(MyList)

• OUTPUT—
• ['apple', 'banana']
List continued…
Pop with parameter
• MyList = ['apple', 'banana', 'cherry']
• MyList.pop(1)
• print(MyList)

• OUTPUT—
• ['apple', 'cherry']
clear( ) method

• This method removes all items from the list.



• MyList = ['apple', 'banana', 'cherry']
• MyList.clear()
• print(MyList)

• OUTPUT—
• []
extend( ) method

This method adds one list at the end of another list.

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

OUTPUT—

['a', 'b', 'c', 1, 2, 3]



count( ) method

This method counts the occurrence of an item in


the list.

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

This method reverses the items of the list.

MyList = ['A','B','C','D','E','F']

MyList.reverse( )
print(MyList)

OUTPUT—

['F', 'E', 'D', 'C', 'B', 'A']


The sort Method

The sort method rearranges the elements of a list


so they appear in ascending order (from the lowest
value to the highest value).
>>>my_list = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
>>>print('Original order:', my_list)
>>>my_list.sort()
>>>print('Sorted order:', my_list)
Output:
• Original order: [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
• Sorted order: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Sort : Other example
>>>my_list = ['beta', 'alpha', 'delta', 'gamma']
>>>print('Original order:', my_list)
>>>my_list.sort()
>>>print('Sorted order:', my_list)
When this code runs it will display the following:
• Original order: ['beta', 'alpha', 'delta',
'gamma']
• Sorted order: ['alpha', 'beta', 'delta', 'gamma']
Sorting in reverse
But if we want to sort the elements of the list into descending
order, then we must mention ‘reverse=True’ in the sort( )
method.
x.sort(reverse=True)
Example—

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?

• How do you find the lowest and highest values in a list?

• Assume the following statement appears in a program:


names = []
Which of the following statements would you use to
add the string ‘python’ to the list at index 0? Why
would you select this statement instead of the other?
a. names[0] = ‘python'
b. names.append(‘python')
Write a python function
which accepts a list as an argument and returns the sum of the list’s
elements.
Solution
• def get_total(value_list):
• total = 0
• for num in value_list:
• total += num
• return total

• numbers = [2, 4, 6, 8, 10]


• print('The total is', get_total(numbers))
Quiz questions
my_list=[‘two’,5,[‘one’,2]]
print(len(my_list)
----------------------------------------------------------------
Mix_list=[‘pet’,’dog’,5,’cat’, ’good’,’dog’]
Mix_list.count(‘dog’)
--------------------------------------------------------------
mylist=[‘red’,3]
mylist.extend(‘green’)
Print(len(mylist))
Solutions
• 3
• 2
• [‘red’, 3, ’g’, ’r’, ’e’, ’e’, ’n’]
Some List Based Questions for Practice
• Using the list L, what is the value of each of
the expressions (a) through (e) below?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan',
'Tesla']
(a) len(L)
(b) len(L[1])
(c) L[2] Toyota
(d) L[4] + '***'
(e) L[1] == L[2]
• Using the list L, what is the value of each of
the expressions (a) through (e) below?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan',
'Tesla']
(a) len(L)
(b) len(L[1])
(c) L[2] Toyota
(d) L[4] + '***'
(e) L[1] == L[2]
• >>> L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
• >>> len(L)
• 5
• >>> len(L[1])
• 9
• >>> L[2]Toyota
• SyntaxError: invalid syntax
• >>> L[4] + '***'
• 'Tesla***'
• >>> L[1] == L[2]
• False
• >>>
Question
• Using the list defined below, what does Python print
when these statements are executed?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
(a)
for x in L:
print('Item:', x)
(b)
size = len(L)
for i in range(size):
print(i+1, L[i])
print("Total count:", size)
• Item: Ford
• Item: Chevrolet
• Item: Toyota
• Item: Nissan
• Item: Tesla
• 1 Ford
• Total count: 5
• 2 Chevrolet
• Total count: 5
• 3 Toyota
• Total count: 5
• 4 Nissan
• Total count: 5
• 5 Tesla
• Total count: 5
• Write a program to search an element in a list
Linear search
• def linear_search(My_list,key):
• for i in range(len(My_list)):
• if My_list[i]==key:
• return i

• return -1
• My_list=[1,5,6,10,15,45,67]
• result=linear_search(My_list,32)
• if(result!=-1):
• print("Element found at position",result)
• else:
• print("Element not found")
Stack using List
stack = []

# pop() fucntion to pop


# append() function to # element from stack in
push # LIFO order
# element in the stack print('\nElements poped from
stack.append('a') stack:')
stack.append('b') print(stack.pop())
stack.append('c') print(stack.pop())
print(stack.pop())

print('Initial stack') print('\nStack after elements


print(stack) are poped:')
print(stack)
Queue Using List
• Program to perform binary search in a list
• def binary_search(My_list,key):
• low=0
• high=len(My_list)-1
• while low<=high:
• mid=(low+high)//2
• print(My_list[mid])

• 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.

List comprehension contains very less code usually one


line to perform a task.

• [exp for val in collection]


• [expr for val in collection if<test>]
• [expr for val in collection if<test1> and <test2>]
• [expr for val1 in collection1 and val in collection2]]
e.g.
• Squares=[]
• for i in range(1,101):
squares.append(i**2)

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

• Write list comprehension to generate [0, 10,


20, 30, 40, 50, 60, 70, 80, 90] this list

• 1
mylist = [x+3 for x in range(-2,98,3)]
print(mylist)
Or b=[3*i-2 for i in range(1,35)]
• 2
mylist = [x*5 for x in range (1, 11)]
print(mylist)

• 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:

['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even',


'Odd', 'Even', 'Odd']

Extract the vowels using
comprehension

line=‘ This is python programming language class’

Vowels= [s for s in line if s in “aeiou”]


Tuple in Python
CREATING TUPLES

We create a tuple by writing elements separated by


commas inside parenthesis ( ).
Example—
T1= ( ) #empty tuple# type is tuple
T=(4) #not a tuple but int
T2 = (10,) #tuple with one element
T3 = (12, 20.5, ‘Delhi’, ‘UP’)
T4 = (10, 20, 30, 40)
T5 = 10, 20, 30, 40 #tuple packing
Examples
• Note:
• >>> T1=()
• >>> type(T1)
• <class 'tuple'>
• >>> T2=(10,)
• >>> type(T2)
• <class 'tuple'>
• >>> T3=(10)
• >>> type(T3)
• <class 'int'>
• >>> T4=10,20,30,40
• >>> type(T4)
• <class 'tuple'>

• So a single value in parenthesis is not a tuple.
Changing a Tuple

Unlike lists, tuples are immutable data type.


This means that the items of a tuple cannot be changed once it has been
created. But, if the item is itself a mutable data type like list, its nested items
can be changed.

Example—

Tup = (1, 2, 3, [4, 5]) OUTPUT—


#Tup[2] = 6 (1, 2, 3, [4, 8])
#Error:'tuple' object does
not support item
assignment
Tup[3][1] = 8
print(Tup)
THE tuple( ) FUNCTION for type casting
It is used to convert string or lists into tuple.
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

Tup2=tuple("CORE PYTHON") OUTPUT—


1. print(Tup2) 1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y',
2. print(Tup2[0]) 'T', 'H', 'O', 'N')
3. print(Tup2[5]) 2. C
4. print(Tup2[-5]) 3. P
5. print(Tup2[-7]) 4. Y
6. print(Tup2[-1]) 5.
6. N
Example—
(Indexing and slicing)
Tup=tuple("CORE PYTHON") Output
1. print(Tup) 1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y',
2. print(Tup[0:4]) 'T', 'H', 'O', 'N')
3. print(Tup[6:]) 2. ('C', 'O', 'R', 'E')
4. print(Tup[0:]) 3. ('Y', 'T', 'H', 'O', 'N')
5. print(Tup[-1::-1]) 4. ('C', 'O', 'R', 'E', ' ', 'P', 'Y',
'T', 'H', 'O', 'N')
5. ('N', 'O', 'H', 'T', 'Y', 'P', ' ',
'E', 'R', 'O', 'C')
OPERATORS 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

• It is the repetition operator that is used to repeat


or replicate the items of a tuple.

Example—
Tup=(1,2,3)
Tup2=Tup * 2
print(Tup2)
OUTPUT—
(1, 2, 3, 1, 2, 3)
How to sort elements in Tuple

Let Tup=(1,4,2,5,3) be a tuple.


Different ways to sort this 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—

Using sorted( ) method.


Syntax is sorted( Iterable, reverse=True)

Here Iterable is the tuple name


To sort in descending order, write reverse=True

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

• We cannot change the items in a tuple. Also


we cannot delete or remove items from a
tuple.
• But deleting a tuple entirely is possible using
the keyword del.
Example—

print(Tup_new)
Tup_new = ('p','y','t','h','o','n') # NameError: name 'my_tuple'
print(Tup_new) is not defined

# del Tup_new[3] OUTPUT—


# TypeError: 'tuple' object
doesn't support item ('p', 'y', 't', 'h', 'o', 'n')
deletion NameError: name 'Tup_new' is
not defined
del Tup_new
# to delete an entire tuple

Membership Operator in Tuple
We can test if an item exists in a OUTPUT—
tuple or not, using the
keyword in and not in.

1. ('p', 'y', 't', 'h', 'o', 'n')


Tup_new = ('p','y','t','h','o','n') 2. True
1. print(Tup_new) 3. False
2. print('p' in Tup_new) 4. False
3. print('e' in Tup_new)
4. print('n' not in Tup_new)
Methods
>>>L=[]
>>> dir(L)
['append', 'count', 'extend', 'index', 'insert',
'pop','remove', 'reverse', 'sort']
>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples are more efficient

• Since Python does not have to build tuple structures


to be modifiable, they are simpler and more efficient
in terms of memory use and performance than lists
• So in our program when we are making “temporary
variables” we prefer tuples over lists
• import sys
• List1=[1,2,3,4]
• Tuple1=(1,2,3,4)
• print("List size", sys.getsizeof(List1))
• print("Tuple size", sys.getsizeof(Tuple1)) 96,80
Tuples are faster
import timeit
list_test=timeit.timeit(stmt="[1,2,3,4,5]",number=100000)
tuple_test=timeit.timeit(stmt="(1,2,3,4,5)",number=100000
)
print("List time",list_test)
print("Tuple time",tuple_test)

List time 0.01713409426894973


Tuple time 0.002381077617228944
Tuples and Assignment

• We can also put a tuple on the left-hand side of an


assignment statement
• We can even omit the parentheses
>>> (x, y) = (4, 'fred')
>>> print y
fred
>>> (a, b) = (99, 98)
>>print (a)
>>99
Updating Tuples:
• Tuples are immutable which means you cannot update them or change
values of tuple elements. But we able able to take portions of an existing
tuples to create a new tuples as follows:
• Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
tup3 = tup1 + tup2;
print tup3;
This will produce following result:
(12, 34.56, 'abc', 'xyz')
Basic Tuples Operations:
• 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 prior 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): 123 Iteration
print x,
Tuple vs List
• Declared with () • Declared with []
• Immutable • Mutable
• Faster • Slower
• Less memory required • More memory usage
• Limited method • Many methods
• Tuples can be dictionary • Lists cannot be dictionary
keys. keys.
• Efficient for temporary • Efficient for dynamic data
variables or fixed data • Data is less secure
• Data can be more secured
107
• tuple1 = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• tinytuple = (123, 'john')
• print(tuple1+tinytuple)

#('abcd', 786, 2.23, 'john', 70.2, 123, 'john')


Dictionaries in Python

• A dictionary represents a group of items/elements


arranged in the form of key : value pair.
• In Dictionary, the first element is the key and second
element is the value associated with the corresponding
key.
• All the elements are enclosed within the curly braces{
}.
• Example—
• dict = {1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’}

• Dictionary key value
• Name
Creating Dictionary
# Creating Dictionary with Integer Keys

Dict = {1: ‘python', 2: ‘Program', 3: ‘example'}


print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary with Mixed keys

Dict = {'Name': ‘Python', 1: [1, 2, 3, 4]}


print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
dict( ) function to create a dictionary
in Python
• Dictionary can also be created with the help of
the built-in function dict( ). An empty
dictionary can also be created by using curly
braces{ }.
• # Creating an empty Dictionary
• Dict = {}
print("This is an empty Dictionary: ")
print(Dict)
Accessing Values in Dictionary:
• To access dictionary elements, you use the familiar
square brackets along with the key to obtain its
value:
• Example:

• This will produce following result:


dict['Name']: Zara
dict['Age']: 7
• If we attempt to access a data item with a key which
is not part of the dictionary, we get an error as
follows:
dict = {'Name': 'Zara', 'Age': 7,
'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
• This will produce following result:
dict['Zara']:
Traceback (most recent call last): File
"test.py", line 4, in <module> print
"dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary:
• You can update a dictionary by adding a new entry or item (i.e., a key-
value pair), modifying an existing entry, or deleting an existing entry as
shown below:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
• This will produce following result:
dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements:
• You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.
• To explicitly remove an entire dictionary, just use the del statement:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'};
del dict['Name']; # remove entry with key
'Name' d
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

• Note: del() method is discussed in subsequent section.


Properties of Dictionary Keys:
• Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys:
• (a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins.
• Example:

dict = {'Name': 'Zara', 'Age': 7,


'Name': 'Manni'};
print "dict['Name']: ",
dict['Name'];
• This will produce following result:
dict['Name']: Manni
• (b) Keys must be immutable. Which means you can
use strings, numbers, or tuples as dictionary keys
but something like ['key'] is not allowed.
• Example:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
• This will produce following result. Note an exception raised:
Traceback (most recent call last):
File "test.py", line 3, in <module> dict = {['Name']:
'Zara', 'Age': 7};
TypeError: list objects are unhashable
Built-in General Functions applicable on Dictionary:
SN Function with Description
1 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
2 str(dict)
Produces a printable string representation of a dictionary
3 type(variable)
Returns the type of the passed variable. If passed variable is dictionary
then it would return a dictionary type.
Inbuilt Methods
From Key Function
• >>> dic={"name":"Sanjeev","address":“KIET"}
• >>> dic
{'address': ‘KIET', 'name': 'Sanjeev'}
• >>> dic.fromkeys("sanjeev","fromkey")
{'s': 'fromkey', 'j': 'fromkey', 'v': 'fromkey', 'n':
'fromkey', 'a': 'fromkey', 'e': 'fromkey'}
• >>> dic.fromkeys(dic,"fromkey")
{'address': 'fromkey', 'name': 'fromkey'}
dict.clear()

• D.clear() -> None. Remove all items from D.


d.copy
• D.copy() -> Returns a copy of D
dict.get(key)

• D.get(k) -> D[k] if k in D, else returns None(By


default, else can be sent as parameter while
calling
dict.items(), dict.keys(), dict.values()
Returns corresponding list
d.update()
• The update() method updates the dictionary with the
elements from the another dictionary object or from an
iterable of key/value pairs.
• The update() method takes either a dictionary or an iterable
object of key/value pairs (generally tuples).
Pop and popitem()
• The pop() method removes and returns an
element from a dictionary corresponding to
the given key.
• The popitem() returns and removes an
arbitrary(LIFO) element (key, value) tuple pair
from the dictionary. Does not take any
argument.
Example
Setdefault()
• The set default() method returns the value of a key (if the
key is in dictionary). If not, it inserts key with a value to
the dictionary.

Return Value from set default()


• The set default() returns:
• value of the key if it is in the dictionary
• None: if key is not in the dictionary and default value is not
specified
• Specified default_value if key is not in the dictionary
• Key and correponding value if specified is added in
dictionary and mentioned value is returned
Set default example
Iteration through dictionary:

>>> 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']

Can be applied on tuples as well.


Write a function histogram that takes string as parameter and
generates a frequency of character contained in it.

(Hint: Use Dictionary to store character as key and count as value in


dictionary. Initially you can take empty dictionary)
Solution
• S=“AAPPLE”
• D=dict() {‘A’:2,’P’:2,’L’:1,’E’:1}
• for C in S:
• if C not in D:
• D[C]=1
• else:
• D[C]=D[C]+1
• print(D)
Write a program to print and store squares
of upto n numbers in the dictionary
• {1:1,2:4,3:9…….n:n2}
Solution
• def sq_of_numbers(n):
• d=dict()
• for i in range(1,n+1):
• if i not in d:
• d[i]=i*i
• return d
• print("sqaures of numbers:")
• Z=sq_of_numbers(5)
• print(Z)
160(List of tuples can be converted
into dictionary)
• Describe what the following statements do
and write their output.
If lt = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]
lt=dict(lt)
>>>lt
>>> lt.clear()
>>> lt
Solution
• {'a': 'b', 'e': 'f', 'c': 'd'}
• {}
More on dictionary

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?

my_dict = {'a': 10, 'b': 20, 'c': 30}


1. print(my_dict.get('c'))
2. print(my_dict.get('d'))
3. print(my_dict.get('d',-1))
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

• A set in Python is an unordered collection of


unique elements without duplicate elements
in the set.
• Unlike Tuple, Set is Mutable means that once
it created, we can change its contents.
• This data type support mathematical set
operations.
How to create a set
As Set is created by enclosing all elements with a curly braces { } and
separated by commas.
It can have any number of items and that can be of different types (integer,
float, tuple, string etc.).

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)

set2 = {5, "Python", (1, 2, 3, 4, 5)}


print(set2)

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—

set4 = {1, 2, 3,[4, 5]}


print(set4)

OUTPUT—
TypeError: unhashable type: 'list'
Example—

1. set5 = {1, 2, 3,{4, 5}}


2. print(set5)

OUTPUT—
Type Error: unhashable type: 'set'

Note: An empty curly braces { } will make an empty


dictionary in Python.
To make a set without any elements we use
the set( ) function without any argument.
Convert List to Set and Tuple to 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)

set2.remove(3) #set2.discard(3)(No error)


print(set2)

OUTPUT—
{1, 2, 3, 4, 5}
{1, 2, 4, 5}
issubset( setName)

• This method checks if one set is subset of another set


or not.
• It give output in Boolean i,e. True or False
• Example—

1. s1={10,20,30,40}
2. s2={10,20,30,40,50}
3. print(s1.issubset(s2))

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)

• This method checks if one set is superset of another set


or not. It give output in Boolean i,e. True or False
Example—

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

The intersection of two sets S1 and S2 is a set of elements


that are present in both S1 and S2.
Syntax is: set1.intersection(set2)
Symbol is: &
• Example—
• s1={10,20,30}
• s2={10,20,30,40,50}
• print(s1.intersection(s2))

• OUTPUT—
• {10, 20, 30}
Example
1. s1={10,20,30}
2. s2={10,20,30,40,50}
3. s3=s1 & s2
4. print(s3)

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

• The symmetric difference of two sets S1 and S2 is a set of


elements that are present in either in S1 or in S2 but not in
both sets.
Syntax is:
set1.symmetric_difference(set2)
Symbol is:^
Example—
1. s1={10,20,30,40,50}
2. s2={30,40,50,60,70}
3. print(s1.symmetric_difference(s2))
OUTPUT—
{20, 70, 10, 60}
Example using symbol
Example—
s1={10,20,30,40,50}
s2={30,40,50,60,70}
s3=s1 ^ s2
print(s3)

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—

Myset = {"dell", "sony", "lenovo", "hp"}


Myset.add("samsung")
print(Myset)

OUTPUT—
{'lenovo', 'sony', 'dell', 'hp', 'samsung'}
Example— Update

Myset = {"dell", "sony", "lenovo", }


Myset.update(["apple","hp","samsung"])
print(Myset)

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)))

You might also like