Unit 3
Unit 3
3.1 Functions
3.2 Strings
3.3 Python Data Structure
3.4 Higher Order Functions
3.1 Functions
Functions
Python enables its programmers to break up a program into segments commonly known as functions, each
of which can be written more or less independently of the others. Every function in the program is
supposed to perform a well-defined task.
• A function, f that uses another function g, is known as the calling function and g is known as the called function.
• The inputs that the function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it is said to return that result.
• The calling function may or may not pass parameters to the called function. If the called function accepts
arguments, the calling function will pass parameters, else not.
• Function declaration is a declaration statement that identifies a function with its name, a list of arguments
that it accepts and the type of data it returns.
• Function definition consists of a function header that identifies the function, followed by the body of the
function containing the executable code for that function.
Function Call
The function call statement invokes the function. When a function is invoked the program control jumps to
the called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function.
Function Parameters
A function can take parameters which are nothing but some values that are passed to it so that the function
can manipulate them to produce the desired result. These parameters are normal variables with a small
difference that the values of these variables are defined (initialized) when we call the function and are then
passed to the function.
Function name and the number and type of arguments in the function call must be same as that given in the
function definition.
If the data type of the argument passed does not matches with that expected in function then an error is
generated. Example: 6
A variable which is defined within a function is local to that function. A local variable can be accessed from
the point of its definition until the end of the function in which it is defined. It exists as long as the function is
executing. Function parameters behave like local variables in the function. Moreover, whenever we use the
assignment operator (=) inside a function, a new local variable is created.
Global variables are those variables which are defined in the main body of the program file. They are visible
throughout the program file. As a good programming habit, you must try to avoid the use of global variables
because they may get altered by mistake and then result in erroneous output.
Example:
10
Example:
11
12
In the required arguments, the arguments are passed to a function in correct positional order. Also, the number
of arguments in the function call should exactly match with the number of arguments specified in the
function definition
Examples:
13
Keyword Arguments
When we call a function with some values, the values are assigned to the arguments based on their position.
Python also allow functions to be called using keyword arguments in which the order (or position) of the
arguments can be changed. The values are not assigned to arguments according to their position but based
on their name (or keyword).
Keyword arguments are beneficial in two cases.
• First, if you skip arguments.
• Second, if in the function call you change the order of parameters.
Example:
14
Example:
16
Example:
17
• A lambda function can take any number of arguments, but can only have one expression.
Functions as objects
In Python, a function can be assigned to a variable. This assignment does not call
the function, instead a reference to that function is created. Consider the below
example, for better understanding.
Example:
def shout(text):
return text.upper()
print(shout('Hello'))
yell = shout
print(yell('Hello'))
Output:
HELLO
HELLO
In the above example, a function object referenced by shout and creates a second
name pointing to it.
Functions are like objects in Python, therefore, they can be passed as argument to other
functions. Consider the below example, where we have created a function greet which takes a
function as an argument.
Example:
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)
Output:
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
def create_adder(x):
def adder(y):
return x + y
return adder
add_15 = create_adder(15)
print(add_15(10))
Output:
25
The filter() function filters the given sequence with the help of a function that
tests each element in the sequence to be true or not. OR
The filter() function returns an iterator where the items are filtered through a function to test
if the item is accepted or not.
Syntax
filter(function, sequence)
Parameters:
function: function that tests if each element of a sequence true or
not.
sequence: sequence which needs to be filtered, it can be sets, lists,
tuples, or containers of any iterators.
Returns:
returns an iterator that is already filtered.
Example
l= [1,4,5,6,7,10]
nl=list(filter(lambda x : (x>5)),l)
print(nl)
Output: [6,7,10][
Syntax
map(function, iterables)
Parameter Values
Parameter Description
Iterable Required. A sequence, collection or an iterator object. You can send as many
iterables as you like, just make sure the function has one parameter for each
iterable.
Example
1. Calculate the length of each word in the tuple:
def myfunc(n):
return len(n)
print(list(x))
Output: [5,6,6][5,} 6, 6]
a=[1,2,3]
b=map(lambda x: x*x ,a)
print(list(b))
Output: [1, 4, 9] [
• The function passed as an argument is applied to the first two elements of the
iterable.
• After this, the function is applied to the previously generated result and the next
element in the iterable.
• This process continues until the whole iterable is processed.
• The single value is returned as a result of applying the reduce function on the
iterable.
Example:
import functools as ft
data=[10,32,3,5,8,9]
sum=ft.reduce(lambda a,b:a+b ,data)
print("sum of numbers is-->",sum)
We get the result as 67 because the steps followed by the reduce function
calculate the result of the following equation(((((10+32)+3)+5)+8)+9). First, the
addition of 10 and 32 is done, and the result of this addition is further done with
all the other elements of the list one by one.
Indexing: Individual characters in a string are accessed using the subscript ([ ]) operator. The expression in
brackets is called an index. The index specifies a member of an ordered set and in this case it specifies the
character we want to access from the given set of characters in the string.
The index of the first character is 0 and that of the last character is n-1 where n is the number of characters
in the string. If you try to exceed the bounds (below 0 or above n-1), then an error is raised.
2
Strings
Traversing a String: A string can be traversed by accessing character(s) from one index to another. For
example, the following program uses indexing to traverse a string from first character to the last.
Example:
Examples:
10
Examples:
11
Examples:
12
Comparing Strings
13
Examples:
14
15
Lists
List is a versatile data type available in Python. It is a sequence in which elements are written as a list of
comma-separated values (items) between square brackets. The key feature of a list is that it can have
elements that belong to different data types.The syntax of defining a list can be given as,
List_variable = [val1, val2,...]
Examples:
Similar to strings, lists can also be sliced and concatenated. To access values in lists, square brackets are used
to slice along with the index or indices to get value stored at that index. The syntax for the slice operation is
given as, seq = List[start:stop:step]
Example:
Example:
Cloning Lists
If you want to modify a list and also keep a copy of the original list, then you should create a separate copy
of the list (not just the reference).This process is called cloning.The slice operation is used to clone a list.
Example:
List Methods
Python List comprehension provides a much more short syntax for creating a new list based on the
values of an existing list.
Syntax
newList = [ expression/(element) for element in oldList if condition ]
A Python list comprehension consists of brackets containing the expression, which is executed for each element
along with the for loop to iterate over each element in the Python list.
Examples:
# 1. printing the even numbers from 0 to 10.
list = [i for i in range(11) if i % 2 == 0]
print(list)
Output:
[0, 2, 4, 6, 8, 10]
#2. print all positive values of ginen list using list comprehension
data =[23,56,-2,7,-65,0,-43]
positive=[i for i in data if i>=0]
print(positive)
Output:
[23, 56, 7, 0]
Examples:
16
Tuple
Like lists, tuple is another data structure supported by Python. It is very similar to lists but differs in two
things.
• First, a tuple is a sequence of immutable objects. This means that while you can change the value of one or
more items in a list, you cannot change the values in a tuple.
• Second, tuples use parentheses to define its elements whereas lists use square brackets.
Creating Tuple
Creating a tuple is very simple and almost similar to creating a list. For creating a tuple, generally you need
to just put the different comma-separated values within a parentheses as shown below.
Tup1 = (val 1, val 2,...)
where val (or values) can be an integer, a floating number, a character, or a string.
21
22
Example:
23
Examples:
24
25
27
Examples:
28
The list is better for performing operations, A Tuple data type is appropriate for
3
such as insertion and deletion. accessing the elements
Sets is another data structure supported by Python. Basically, sets are same as lists but with a difference that
sets are lists with no duplicate entries.Technically, a set is a mutable and an unordered collection of items.This
means that we can easily add or remove items from it.
A set is created by placing all the elements inside curly brackets {}, separated by comma or by using the
built-in function set().The syntax of creating a set can be given as,
33
Set Operations
34
35
Set Operations
36
37
Dictionaries
Dictionary is a data structure in which we store values as a pair of key and value. Each key is separated from its
value by a colon (:), and consecutive items are separated by commas.The entire items in a dictionary are
enclosed in curly brackets({}).The syntax for defining a dictionary is
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
If there are many keys and values in dictionaries, then we can also write just one key-value pair on a line
to make the code easier to read and understand.This is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….}
Example:
38
Example:
39
Example:
40
41
Deleting Items
You can delete one or more items using the del keyword. To delete or remove all the items in just one
statement, use the clear() function. Finally, to remove an entire dictionary from the memory, we can gain
use the del statement as del Dict_name.The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:
42
43
Nested Dictionaries
Example:
44
45
46
47
Python also allows you to use string formatting feature with dictionaries. So you can use %s, %d, %f, etc. to
represent string, integer, floating point number, or any other data.
Example: Program that uses string formatting feature to print the key-value pairs stored in the dictionary
49
50