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

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

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.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

1|Page Python Programming (KNC-402)


Need for Functions
Each function to be written and tested separately.
• Understanding, coding and testing multiple separate functions is far easier.
Without the use of any function, then there will be countless lines in the code and maintaining it will be a big
mess.
• Programmers use functions without worrying about their code details. This speeds up program development,
by allowing the programmer to concentrate only on the code that he has to write.
Different programmers working on that project can divide the workload by writing different functions.
• Like Python libraries, programmers can also make their functions and use them from different point in the
main program or any other program that needs its functionalities.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Function Declaration and Definition

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

2|Page Python Programming (KNC-402)


Function Definition
Function blocks starts with the keyword def.
• The keyword is followed by the function name and parentheses (( )).
• After the parentheses a colon (:) is placed.
• Parameters or arguments that the function accept are placed within parentheses.
• The first statement of a function can be an optional statement - the docstring describe what the function does.
• The code block within the function is properly indented to form the block code.
• A function may have a return[expression] statement.That is, the return statement is optional.
• You can assign the function name to a variable. Doing this will allow you to call same function using the name
of that variable. Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

3|Page Python Programming (KNC-402)


Local and Global Variables

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.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

4|Page Python Programming (KNC-402)


Local and Global Variables
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Using the Global Statement


To define a variable defined inside a function as global, you must use the global statement. This declares the
local or the inner variable of the function to have module scope.

Example:

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

5|Page Python Programming (KNC-402)


Resolution of names
Scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope is that
particular block. If it is defined in a function, then its scope is all blocks within that function.
When a variable name is used in a code block, it is resolved using the nearest enclosing scope. If no variable of
that name is found, then a NameError is raised. In the code given below, str is a global string because it has
been defined before calling the function.

Example:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

The Return Statement


The syntax of return statement is,
return [expression]
The expression is written in brackets because it is optional. If the expression is present, it is evaluated and the
resultant value is returned to the calling function. However, if no expression is specified then the function will
return None. Example:

The return statement is used for two things.


• Return a value to the caller
• To end and exit a function and go back to its caller

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

6|Page Python Programming (KNC-402)


Required Arguments

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

7|Page Python Programming (KNC-402)


Default Arguments
Python allows users to specify function arguments that can have default values.This means that a function can be
called with fewer arguments than it is defined to have.That is, if the function accepts three parameters, but function
call provides only two arguments, then the third parameter will be assigned the default (already specified) value.
The default value to an argument is provided by using the assignment operator (=). Users can specify a
default value for one or more arguments.

Example:

16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

8|Page Python Programming (KNC-402)


Lambda Functions Or Anonymous Functions
Lambda or anonymous functions are so called because they are not declared as other functions using the def
keyword. Rather, they are created using the lambda keyword. Lambda functions are throw-away functions,
i.e. they are just needed where they have been created and can be used anywhere a function is required. The
lambda feature was added to Python due to the demand from LISP programmers.
Lambda functions contain only a single line. Its syntax can be given as,

Example:

17

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

• A lambda function can take any number of arguments, but can only have one expression.

9|Page Python Programming (KNC-402)


Higher Order Functions

A function is called Higher Order Function if it contains other functions as a


parameter or returns a function as an output.

Properties of higher-order functions:


• A function is an instance of the Object type.
• You can store the function in a variable.
• You can pass the function as a parameter to another function.
• You can return the function from a function.
• You can store them in data structures such as hash tables, lists, …

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:

# Python program to illustrate functions

# can be treated as objects

def shout(text):

return text.upper()

print(shout('Hello'))

# Assigning function to a variable

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.

10 | P a g e Python Programming (KNC-402)


Passing Function as an argument to other function

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:

# Python program to illustrate functions

# can be passed as arguments to other functions

def shout(text):

return text.upper()

def whisper(text):

return text.lower()

def greet(func):

# storing the function in a variable

greeting = func("Hi, I am created by a


function \

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.

11 | P a g e Python Programming (KNC-402)


Returning function
As functions are objects, we can also return a function from another function. In the below
example, the create_adder function returns adder function.
Example:

# Python program to illustrate functions

# Functions can return another function

def create_adder(x):

def adder(y):

return x + y

return adder

add_15 = create_adder(15)

print(add_15(10))

Output:
25

12 | P a g e Python Programming (KNC-402)


Python filter() Function

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

13 | P a g e Python Programming (KNC-402)


Python map() Function
The map() function executes a specified function for each item in an iterable. The item is sent to
the function as a parameter.

Syntax
map(function, iterables)

Parameter Values

Parameter Description

Function Required. The function to execute for each item

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)

x = map(myfunc, ('apple', 'banana', 'cherry'))

print(list(x))

Output: [5,6,6][5,} 6, 6]

2. square the every numbers of the list:

a=[1,2,3]
b=map(lambda x: x*x ,a)
print(list(b))
Output: [1, 4, 9] [

14 | P a g e Python Programming (KNC-402)


Python reduce() Function
The reduce() function in python is a part of the functools module and doesn't return
multiple values; it just returns a single value. OR
The reduce(fun,seq) function is used to apply a particular function passed
in its argument to all of the list elements mentioned in the sequence passed
along.This function is defined in “functools” module.

Steps of how to reduce function works in python:

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

Output: sum of numbers is--> 67

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.

15 | P a g e Python Programming (KNC-402)


Strings
Python treats strings as contiguous series of characters delimited by single, double or even triple quotes.
Python has a built-in string class named "str" that has many useful features. We can simultaneously declare
and define a string by creating a variable of string type.This can be done in several ways which are as follows:
name = "India" graduate = 'N' country = name nationality = str("Indian")

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

16 | P a g e Python Programming (KNC-402)


Concatenating, Appending and Multiplying Strings
Examples:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Strings are Immutable


Python strings are immutable which means that once created they cannot be changed. Whenever you try to
modify an existing string variable, a new string is created.
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

17 | P a g e Python Programming (KNC-402)


String Formatting Operator
The % operator takes a format string on the left (that has %d, %s, etc) and the corresponding values in a tuple
(will be discussed in subsequent chapter) on the right. The format operator, % allow users to construct strings,
replacing parts of the strings with the data stored in variables. The syntax for the string formatting operation
is:
"<Format>" % (<Values>)
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Built-in String Methods and Functions

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

18 | P a g e Python Programming (KNC-402)


Built-in String Methods and Functions

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Built-in String Methods and Functions

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

19 | P a g e Python Programming (KNC-402)


Slice Operation
A substring of a string is called a slice. The slice operation is used to refer to sub-parts of sequences and
strings.You can take subset of string from original string by using [ ] operator also known as slicing operator.

Examples:

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Specifying Stride while Slicing Strings


In the slice operation, you can specify a third argument as the stride, which refers to the number of characters
to move forward after the first character is retrieved from the string. By default the value of stride is 1, so in
all the above examples where he had not specified the stride, it used the value of 1 which means that every
character between two index numbers is retrieved.

Examples:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

20 | P a g e Python Programming (KNC-402)


ord() and chr() Functions
ord() function returns the ASCII code of the character and chr() function returns character represented by
a ASCII number. Examples:

in and not in Operators


in and not in operators can be used with strings to determine whether a string is present in another string.
Therefore, the in and not in operator are also known as membership operators.

Examples:

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Comparing Strings

13

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

21 | P a g e Python Programming (KNC-402)


Iterating String
String is a sequence type (sequence of characters).You can iterate through the string using for loop.

Examples:

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

22 | P a g e Python Programming (KNC-402)


The String Module
The string module consist of a number of useful constants, classes and functions (some of which are
deprecated).These functions are used to manipulate strings.
Examples:

15

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

23 | P a g e Python Programming (KNC-402)


Data Structure: Sequence
A data structure is a group of data elements that are put together under one name. Data structure defines a
particular way of storing and organizing data in a computer so that it can be used efficiently.
Sequence is the most basic data structure in Python. In sequence, each element has a specific index. This
index value starts from zero and is automatically incremented for the next element. In Python, sequence is
the generic term for an ordered set. For example, we have already studied strings which are a sequence of
characters.
Python has some basic built-in functions that help programmers to manipulate elements that form a part
of a sequence.These functions include finding the length of a sequence, finding the largest and smallest
elements in a sequence, etc. Other operations that can be performed on a sequence include indexing, slicing,
adding, multiplying, and checking for membership.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

24 | P a g e Python Programming (KNC-402)


Access Values in Lists

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:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Updating Values in Lists


Once created, one or more elements of a list can be easily updated by giving the slice on the left-hand side of
the assignment operator. You can also append new values in the list and remove existing value(s) from the list
using the append() method and del statement respectively.
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

25 | P a g e Python Programming (KNC-402)


Nested Lists
Nested list means a list within another list. We have already said that a list has elements of different data
types which can include even a list.

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

26 | P a g e Python Programming (KNC-402)


Basic List Operations

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

List Methods

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

27 | P a g e Python Programming (KNC-402)


List Comprehension

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.

Advantages of List Comprehension

• More time-efficient and space-efficient than loops.


• Require fewer lines of code.
• Transforms iterative statement into a formula.

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]

28 | P a g e Python Programming (KNC-402)


Using the enumerate() and range() Functions
enumerate() function is used when you want to print both index as well as an item in the list. The function
returns an enumerate object which contains the index and value of all the items of the list as a tuple.
The range() function is used when you need to print index.

Examples:

16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

29 | P a g e Python Programming (KNC-402)


Utility of Tuples
In real-world applications, tuples are extremely useful for representing records or structures as we call
in other programming languages.These structures store related information about a subject together.
The information belongs to different data types.
For example, a tuple that stores information about a student can have elements like roll_no, name, course,
total marks, avg, etc. Some built-in functions return a tuple. For example, the divmod() function returns two
values—quotient as well as the remainder after performing the divide operation.
Examples:

22

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Accessing Values in a Tuple


Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0.You can even perform
operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple, slice operation is
used along with the index or indices to obtain value stored at that index

Example:

23

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

30 | P a g e Python Programming (KNC-402)


Deleting Elements in Tuple
Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course, you can create a
new tuple that has all elements in your tuple except the ones you don't want (those you wanted to be
deleted).

Examples:

24

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Basic Tuple Operations

25

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

31 | P a g e Python Programming (KNC-402)


Tuples for Returning Multiple Values and Nested Tuples
Examples:

27

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

32 | P a g e Python Programming (KNC-402)


Checking the Index: index() method
The index of an element in the tuple can be obtained by using the index() method. If the element being
searched is not present in the list, then error is generated. The syntax of index() is given as, list.index(obj)
where, obj is the object to be found out.

Examples:

28

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Differences between List and Tuple in Python


Sno LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is


2 The implication of iterations is Time-consuming
comparatively Faster

The list is better for performing operations, A Tuple data type is appropriate for
3
such as insertion and deletion. accessing the elements

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many built-in


5 Lists have several built-in methods
methods.

Unexpected changes and errors are more likely


6 In a tuple, it is hard to take place.
to occur

33 | P a g e Python Programming (KNC-402)


Sets

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,

Example:To create a set, you can write,

33

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Set Operations

34

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

34 | P a g e Python Programming (KNC-402)


Set Operations

35

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Set Operations

36

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

35 | P a g e Python Programming (KNC-402)


Set Operations

37

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

36 | P a g e Python Programming (KNC-402)


Accessing Values

Example:

39

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Adding and Modifying an Item in a Dictionary

Example:

40

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

37 | P a g e Python Programming (KNC-402)


Modifying an Entry
Example:

41

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

38 | P a g e Python Programming (KNC-402)


Sorting Items and Looping over Items in a Dictinonary
Examples:

43

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Nested Dictionaries

Example:

44

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

39 | P a g e Python Programming (KNC-402)


Built-in Dictionary Functions and Methods

45

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Built-in Dictionary Functions and Methods

46

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

40 | P a g e Python Programming (KNC-402)


Built-in Dictionary Functions and Methods

47

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Difference between a List and a Dictionary


First, a list is an ordered set of items. But, a dictionary is a data structure that is used for matching one item
(key) with another (value).
• Second, in lists, you can use indexing to access a particular item. But, these indexes should be a number. In
dictionaries, you can use any type (immutable) of value as an index. For example, when we write Dict['Name'],
Name acts as an index but it is not a number but a string.
• Third, lists are used to look up a value whereas a dictionary is used to take one value and look up another
value. For this reason, dictionary is also known as a lookup table.
Fourth, the key-value pair may not be displayed in the order in which it was specified while defining the
dictionary. This is because Python uses complex algorithms (called hashing) to provide fast access to the items
stored in the dictionary.This also makes dictionary preferable to use over a list of tuples.
48

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

41 | P a g e Python Programming (KNC-402)


String Formatting with Dictionaries

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

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

When to use which Data Structure?


• Use lists to store a collection of data that does not need random access.
• Use lists if the data has to be modified frequently.
• Use a set if you want to ensure that every element in the data structure must be unique.
• Use tuples when you want that your data should not be altered.

50

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

42 | P a g e Python Programming (KNC-402)

You might also like