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

Python Unit 3

Uploaded by

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

Python Unit 3

Uploaded by

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

UNIT-III

Functions
A Python function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.

A top-to-down approach towards building the processing logic involves defining blocks of
independent reusable functions. A Python function may be invoked from any other function by
passing required data (called parameters or arguments). The called function returns its result
back to the calling environment.

Types of Python Functions

Python provides the following types of functions −

 Built-in functions
 Functions defined in built-in modules
 User-defined functions

Python's standard library includes number of built-in functions. Some of Python's built-in
functions are print(), int(), len(), sum(), etc. These functions are always available, as they are
loaded into computer's memory as soon as you start Python interpreter.

The standard library also bundles a number of modules. Each module defines a group of
functions. These functions are not readily available. You need to import them into the memory
from their respective modules.

143
In addition to the built-in functions and functions in the built-in modules, you can also create
your own functions. These functions are called user-defined functions.

Defining a Function in Python


You can define custom functions to provide the required functionality. Here are simple rules to
define a function in Python.

 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
 The first statement of a function can be an optional statement; the documentation string
of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.

Syntax

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.

Once the function is defined, you can execute it by calling it from another function or directly
from the Python prompt.

Example

The following example shows how to define a function greetings(). The bracket is empty so there
aren't any parameters.

The first line is the docstring. Function block ends with return statement. when this function is
called, Hello world message will be printed.

def greetings():
"This is docstring of greetings function"
print ("Hello World")

144
return

greetings()

Calling a Function in Python

Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme() function

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print (str)
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following output −

I'm first call to user defined function!


Again second call to the same function
Pass by Reference vs Value

The function calling mechanism of Python differs from that of C and C++. There are two main

function calling mechanisms: Call by Value and Call by Reference.

When a variable is passed to a function, what does the function do to it? If any changes to its
variable doesnot get reflected in the actual argument, then it uses call by value mechanism. On
the other hand, if the change is reflected, then it becomes call by reference mechanism.

145
C/C++ functions are said to be called by value. When a function in C/C++ is called, the value

of actual arguments is copied to the variables representing the formal arguments. If the function
modifies the value of formal aergument, it doesn't reflect the variable that was passed to it.

Function Arguments
The process of a function often depends on certain data provided to it while calling it. While
defining a function, you must give a list of variables in which the data passed to it is collected.
The variables in the parentheses are called formal arguments.

When the function is called, value to each of the formal arguments must be provided. Those are
called actual arguments.

146
Example

Let's modify greetings function and have name an argument. A string passed to the function as
actual argument becomes name variable inside the function.

def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return

greetings("Samay")
greetings("Pratima")
greetings("Steven")

It will produce the following output −

Hello Samay
Hello Pratima
Hello Steven
Types of Function Arguments

Based on how the arguments are declared while defining a Python function, they are classified
into the following categories −

 Positional or required arguments


 Keyword arguments
 Default arguments
 Positional-only arguments
 Keyword-only arguments
 Arbitrary or variable-length arguments
Order of Arguments

A function can have arguments of any of the types defined above. However, the arguments must
be declared in the following order −

 The argument list begins with the positional-only args, followed by the slash (/) symbol.
 It is followed by regular positional args that may or may not be called as keyword
arguments.
 Then there may be one or more args with default values.
 Next, arbitrary positional arguments represented by a variable prefixed with single
asterisk, that is treated as tuple. It is the next.

147
 If the function has any keyword-only arguments, put an asterisk before their names start.
Some of the keyword-only arguments may have a default value.
 Last in the bracket is argument with two asterisks ** to accept arbitrary number of
keyword arguments.

The following diagram shows the order of formal arguments −

PASSING ARGUMENTS
Python uses pass by reference mechanism. As variable in Python is a label or reference to the
object in the memory, the both the variables used as actual argument as well as formal arguments
really refer to the same object in the memory. We can verify this fact by checking the id() of the
passed variable before and after passing.

def testfunction(arg):
print ("ID inside the function:", id(arg))

var="Hello"
print ("ID before passing:", id(var))
testfunction(var)

If the above code is executed, the id() before passing and inside the function is same.

ID before passing: 1996838294128


ID inside the function: 1996838294128

The behaviour also depends on whether the passed object is mutable or immutable. Python
numeric object is immutable. When a numeric object is passed, and then the function changes the
value of the formal argument, it actually creates a new object in the memory, leaving the original
variable unchanged.

def testfunction(arg):
print ("ID inside the function:", id(arg))

148
arg=arg+1
print ("new object after increment", arg, id(arg))

var=10
print ("ID before passing:", id(var))
testfunction(var)
print ("value after function call", var)

It will produce the following output −

ID before passing: 140719550297160


ID inside the function: 140719550297160
new object after increment 11 140719550297192
value after function call 10

Let us now pass a mutable object (such as a list or dictionary) to a function. It is also passed by
reference, as the id() of lidt before and after passing is same. However, if we modify the list
inside the function, its global representation also reflects the change.

Here we pass a list, append a new item, and see the contents of original list object, which we will
find has changed.

def testfunction(arg):
print ("Inside function:",arg)
print ("ID inside the function:", id(arg))
arg=arg.append(100)

var=[10, 20, 30, 40]


print ("ID before passing:", id(var))
testfunction(var)
print ("list after function call", var)

It will produce the following output −

ID before passing: 2716006372544


Inside function: [10, 20, 30, 40]
ID inside the function: 2716006372544
list after function call [10, 20, 30, 40, 100]

149
Keyword Arguments
Python allows to pass function arguments in the form of keywords which are also called named
arguments. Variables in the function definition are used as keywords. When the function is
called, you can explicitly mention the name and its value.

Example

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


# by positional arguments
printinfo ("Naveen", 29)

# by keyword arguments
printinfo(name="miki", age = 30)

By default, the function assigns the values to arguments in the order of appearance. In the second
function call, we have assigned the value to a specific argument

It will produce the following output −

Name: Naveen
Age 29
Name: miki
Age 30

Let us try to understand more about keyword argument with the help of following function
definition −

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

150
division(10,5)
division(5,10)

Since the values are assigned as per the position, the output is as follows −

num:10 den:5 quotient:2.0


num:5 den:10 quotient:0.5

Instead ofpassing the values with positional arguments, let us call the function with keyword
arguments −

division(num=10, den=5)
division(den=5, num=10)

It will produce the following output −

num:10 den:5 quotient:2.0


num:10 den:5 quotient:2.0

When using keyword arguments, it is not necessary to follow the order of formal arguments in
function definition.

Using keyword arguments is optional. You can use mixed calling. You can pass values to some
arguments without keywords, and for others with keyword.

division(10, den=5)

However, the positional arguments must be before the keyword arguments while using mixed
calling.

Try to call the division() function with the following statement.

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

division(num=5, 10)

As the Positional argument cannot appear after keyword arguments, Python raises the following
error message –

151
division(num=5, 10)

^
SyntaxError: non-keyword arg after keyword arg

Keyword-Only Arguments

You can use the variables in formal argument list as keywords to pass value. Use of keyword
arguments is optional. But, you can force the function be given arguments by keyword only. You
should put an astreisk (*) before the keyword-only arguments list.

Let us say we have a function with three arguments, out of which we want second and third
arguments to be keyword-only. For that, put * after the first argument.

The built-in print() function is an example of keyword-only arguments. You can give list of
expressions to be printed in the parentheses. The printed values are separated by a white space by
default. You can specify any other separation character instead with sep argument.

print ("Hello", "World", sep="-")

It will print −

Hello-World

The sep argument is keyword-only. Try using it as non-keyword argument.

print ("Hello", "World", "-")

You'll get different output − not as desired.

Hello World -

Example

In the following user defined function intr() with two arguments, amt and rate. To make
the rate argument keyword-only, put "*" before it.

def intr(amt,*, rate):


val = amt*rate/100
return val

To call this function, the value for rate must be passed by keyword.

152
interest = intr(1000, rate=10)

However, if you try to use the default positional way of calling the function, you get an error.

interest = intr(1000, 10)


^^^^^^^^^^^^^^
TypeError: intr() takes 1 positional argument but 2 were given

Default Arguments
Python allows to define a function with default value assigned to one or more formal arguments.
Python uses the default value for such an argument if no value is passed to it. If any value is
passed, the default value is overridden with the actual value passed.

Example

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

It will produce the following output −

Name: miki
Age 50
Name: miki
Age 35

In the above example, the second call to the function doesn't pass value to age argument, hence
its default value 35 is used.

Let us look at another example that assigns default value to a function argument. The function
percent() is defined as below −

153
def percent(phy, maths, maxmarks=200):
val = (phy+maths)*100/maxmarks
return val

Assuming that marks given for each subject are out of 100, the argument maxmarks is set to 200.
Hence, we can omit the value of third argument while calling percent() function.

phy = 60
maths = 70
result = percent(phy,maths)

However, if maximum marks for each subject is not 100, then we need to put the third argument
while calling the percent() function.

phy = 40
maths = 46
result = percent(phy,maths, 100)

Example

Here is the complete example −

def percent(phy, maths, maxmarks=200):


val = (phy+maths)*100/maxmarks
return val

phy = 60
maths = 70
result = percent(phy,maths)
print ("percentage:", result)

phy = 40
maths = 46
result = percent(phy,maths, 100)
print ("percentage:", result)

It will produce the following output −

percentage: 65.0

154
percentage: 86.0

Variable Length Argument in Python


In this article, we will cover about Variable Length Arguments in Python. Variable-length
arguments refer to a feature that allows a function to accept a variable number of arguments in
Python. It is also known as the argument that can also accept an unlimited amount of data as
input inside the function. There are two types in Python:
 Non – Keyworded Arguments (*args)
 Keyworded Arguments (**kwargs)
What is Python *args?
In Python, *args is used to pass a variable number of arguments to a function. It is used to pass a
variable-length, non-keyworded argument list. These arguments are collected into a tuple within
the function and allow us to work with them.
Feature of Python *args
 To accept a variable number of arguments, use the symbol *; by convention, it is commonly
used with the term args.
 *args enables you to accept more arguments than the number of formal arguments you
previously defined. With *args, you can add any number of extra arguments to your current
formal parameters (including none).
 Using the *, the variable that we associate with the * becomes iterable meaning you can do
things like iterate over it, run some higher-order functions such as map and filter, etc.
In this example, we define a function sum_all that accepts any number of arguments.
The *args syntax collects all the arguments into a tuple named args. Inside the function, we
iterate through the args tuple and calculate the sum of all the numbers passed to the function.

def sum_all(*args):

result = 0

for num in args:

result += num

return result

print(sum_all(1, 2, 3, 4, 5))

Output
15

155
What is Python **kwargs?
In Python, **kwargs is used to pass a keyworded, variable-length argument list. We call kwargs
with a double star. The reason for this is that the double star allows us to pass over keyword
arguments (in any order). Arguments are collected into a dictionary within the function that
allow us to access them by their keys.
Feature of Python **kwargs
 A keyword argument is when you give the variable a name as you provide it into the
function.
 Consider the kwargs to be a dictionary that maps each keyword to the value we pass beside
it. As a result, when we iterate through the kwargs, there appears to be no sequence in which
they were printed.
In this example, the display_info function accepts a variable number of keyword arguments.
Inside the function, we iterate through the kwargs dictionary and print out each key-value pair.

def display_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

display_info(name="Alice", age=30, city="New York")

Output
name: Alice
age: 30
city: New York
Combining *args and **kwargs
You can also use both *args and **kwargs in the same function definition, allowing you to
accept a mix of positional and keyword arguments.

def print_args_and_kwargs(*args, **kwargs):

print("Positional arguments:")

156
for arg in args:

print(arg)

print("Keyword arguments:")

for key, value in kwargs.items():

print(f"{key}: {value}")

print_args_and_kwargs(1, 2, 3, name="Alice", age=30)

Output
Positional arguments:
1
2
3
Keyword arguments:
name: Alice
age: 30
Unpacking Arguments with *args and **kwargs
In this example, we have a function called print_coordinates that takes four arguments (x, y, z,
and w). We then create a list called coordinates containing four values. Using the *coordinates
syntax, we unpack the values from the coordinates list and pass them as arguments to the
print_coordinates function. The function then prints the values in a formatted way.

# Define a function with four arguments

def print_coordinates(x, y, z, w):

157
print(f"X: {x}, Y: {y}, Z: {z}, W: {w}")

# Create a list of coordinates

coordinates = [1, 2, 3, 4]

# Unpack the list into four arguments for the function

print_coordinates(*coordinates)

Output
X: 1, Y: 2, Z: 3, W: 4
Similarly, In this we have a function print_values that takes four arguments (a, b, c, and d). We
create a dictionary called arguments with values corresponding to these arguments, and then we
call the function using the dictionary unpacking (**arguments) to pass the values to the function.

# Define a function with 4 arguments and print their values

def print_values(a, b, c, d):

print(a, b, c, d)

# Create a dictionary with values for the function arguments

arguments = {'a': 10, 'b': 20, 'c': 30, 'd': 40}

158
# Call the function and unpack the dictionary

print_values(**arguments)

Output
10 20 30 40
ANONUMOUS FUNCTION

An anonymous function in Python is one that has no name when it is defined. In Python,
the lambda keyword is used to define anonymous functions rather than the def keyword, which
is used for normal functions. As a result, lambda functions are another name for anonymous
functions.

Syntax

Following is the syntax of the lambda function -

lambda [args] : expression

Although a lambda function can have only one expression, it can have any number of arguments.
A lambda can also be immediately invoked and is written in a single line of code.

Example: Calling a lambda function

The lambda function begins with the keyword lambda and the parameter 'm' and 'n'. The value of
the equation „½ *m * n‟ after ':' is returned to the caller. To make it callable as a named function,
the entire lambda function lambda „m,n : 1/2 * m * n‟ is given to a variable „triangle‟. As
illustrated below, the variable name is converted into the function name so that it can be called
like any other function.

# Finding the area of a triangle


triangle = lambda m,n : 1/2 * m * n
res=triangle(34,24)
print("Area of the triangle: ",res)

Output

159
Following is an output of the above code -

Area of the triangle: 408.0

Alternate Solution

Following is an alternate way to define an anonymous function -

def triangle(m,n):
return 1/2 * m * n
print(triangle(4,6))

Output

Following is an output of the above code -

12.0

Note - It's not necessary for the expression to always return a value. The lambda function as

shown in the following example returns nothing -

company = lambda name: print('EdTech', name)


company('Tutorials Point')

Note − There can only be one expression in a lambda function. It is obvious that it cannot
replace a function whose body contains loops, conditionals, etc.

Using lambda function with Python built-in functions

Using Python's built-in methods is a simple and effective approach to carry out operations with
lambda functions. Due to the fact that these functions can accept lambdas as an argument and be
called immediately, it is possible. When a nameless function is needed for a small duration,
lambda functions are used.

Typically, we utilize it as an argument to a higher-order function in Python (a function that takes


in other functions as arguments). Along with built-in functions like filter(), map(), and others,
lambda functions are used.

160
Using the filter() function

Using the filter function, specific elements can be chosen from a list of elements. Any iterator,
such as lists, sets, tuples, etc., can be used as the sequence. The elements that will be chosen will
depend on a pre-defined constraint. There are two parameters -

 A function that specifies the filtering constraint


 A series of any iterator like lists, tuples, etc.

Example

In the example given below the use of the anonymous function „lambda‟ in the filter() function is
shown. In the first line, a list of numbers named „series‟ is defined. Here, the filtered values
produced by the filter() function are declared in a variable called 'result'. A lambda function that
checks each item in the list and returns true if it is greater than „29‟ is used. Then, print the
outcome that the filter function returned -

series = [23,45,57,39,1,3,95,3,8,85]
result = filter (lambda m: m > 29, series)
print('All the numbers greater than 29 in the series are :',list(result))

Output

Following is an output of the above code -

All the numbers greater than 29 in the series are : [45, 57, 39, 95, 85]
Use in map() function

Every element in a series can have a specific operation performed to it using the map() function.
Similar to filter() function, it requires two parameters i.e. a function that specifies the operation
to be carried out on the elements and one or more sequences.

Example

Following is an example to show the use of the anonymous function „lambda‟ in


the map() function. Here, we define a list called series that has a number of items in it. We
declare the 'result' variable, which will hold the mapped values. A lambda function that returns

161
the cube of each number iteratively evaluated against in the list. The map function's outcome is
then printed.

# printing the cube of numbers given in the list


series = [23,5,1,7,45,9,38,65,3]
result = map (lambda m: m*m*m, series)
print('The cube of each element in the list are :',list(result))

Output

Following is an output of the above code -

The cube of each element in the list are : [12167, 125, 1, 343, 91125, 729, 54872, 274625, 27]
Use in reduce() function

Like the map() function, the reduce function is used to perform an operation on each element in a
sequence. It operates differently from a map, though. The reduce() function performs the

following steps before getting an output -

 Apply the specified operation to the sequence's first two items.


 Store this outcome.
 Execute the operation using the previously saved result and the succeeding element of the
sequence.
 Continue until there are no more elements.

There are two additional parameters -

 A method that specifies the action to be taken


 A series of any iterator like lists, tuples, etc.

Note - The reduce() function is imported from the module named functools. This module

provides higher-order functions such as reduce(), wraps(), cache() etc.

Example

162
In the following example, the use of the anonymous function „lambda‟ in reduce() function is
shown. From the functools module, import the reduce() function. Here, we define a list called
'series' that has a number of items in it. We declare a 'sum' variable that will hold the reduced
value. A lambda function is given that iterates over each list item. It will then give you the result
of the summation of that numbers.

# printing the sum of numbers given in the list from functools


from functools import reduce
series = [23,5,1,7,45,9,38,65,3]
sum = reduce (lambda m,n: m+n, series)
print('The total sum of all the elements in the list is :',sum)

Output

Following is an output of the above code -

The total sum of all the elements in the list is : 196

Fruitful Function(function Returning Value)


The return keyword as the last statement in function definition indicates end of function block,
and the program flow goes back to the calling function. Although reduced indent after the last
statement in the block also implies return but using explicit return is a good practice.

Along with the flow control, the function can also return value of an expression to the calling
function. The value of returned expression can be stored in a variable for further processing.

Example

Let us define the add() function. It adds the two values passed to it and returns the addition. The
returned value is stored in a variable called result.

def add(x,y):
z=x+y
return z

a=10
b=20
result = add(a,b)
print ("a = {} b = {} a+b = {}".format(a, b, result))

163
It will produce the following output −

a = 10 b = 20 a+b = 30

Scope of the variables in a function- Global and local variables


A variable in Python is a symbols name to the object in computer's memory. Python works on
the concept of namespaces to define the context for various identifiers such as functions,
variables etc. A namespace is a collection of symbolic names defined in the current context.

Python provides the following types of namespaces −

 Built-in namespace contains built-in functions and built-in exceptions. They are loaded
in the memory as soon as Python interpreter is loaded and remain till the interpreter is
running.
 Global namespace contains any names defined in the main program. These names
remain in memory till the program is running.
 Local namespace contains names defined inside a function. They are available till the
function is running.

These namespaces are nested one inside the other. Following diagram shows relationship
between namespaces.

164
The life of a certain variable is restricted to the namespace in which it is defined. As a result, it is
not possible to access a variable present in the inner namespace from any outer namespace.

Python globals() Function

Python's standard library includes a built-in function globals(). It returns a dictionary of symbols

currently available in global namespace.

Run the globals() function directly from the Python prompt.

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class
'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__':
<module 'builtins' (built-in)>}

It can be seen that the builtins module which contains definitions of all built-in functions and
built-in exceptions is loaded.

Save the following code that contains few variables and a function with few more variables
inside it.

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
a = 10
b = 20
return a+b

print (globals())

Calling globals() from inside this script returns following dictionary object −

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':


<_frozen_importlib_external.SourceFileLoader object at 0x00000263E7255250>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__':
'C:\\Users\\user\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50,
'result': True, 'myfunction': <function myfunction at 0x00000263E72004A0>}

165
The global namespace now contains variables in the program and their values and the function
object in it (and not the variables in the function).

Any variable created outside a function can be accessed within any function and so they have
global scope. Following is an example to show the usage of global variable in Python:

x=5
y = 10
def sum():
sum = x + y
return sum
print(sum())

This will produce the following result:

15
Python locals() Function

Python's standard library includes a built-in function locals(). It returns a dictionary of symbols
currently available in the local namespace of the function.

Modify the above script to print dictionary of global and local namespaces from within the
function.

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
a = 10
b = 20
c = a+b
print ("globals():", globals())
print ("locals():", locals())
return c
myfunction()

The output shows that locals() returns a dictionary of variables and their values currently
available in the function.

166
globals(): {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
<_frozen_importlib_external.SourceFileLoader object at 0x00000169AE265250>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__':
'C:\\Users\\mlath\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50,
'result': True, 'myfunction': <function myfunction at 0x00000169AE2104A0>}
locals(): {'a': 10, 'b': 20, 'c': 30}

Since both globals() and locals functions return dictionary, you can access value of a variable
from respective namespace with dictionary get() method or index operator.

print (globals()['name']) # displays TutorialsPoint


print (locals().get('a')) # displays 10

Following is a simple example to show the usage of local variables in Python:

def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))
15
Namespace Conflict in Python

If a variable of same name is present in global as well as local scope, Python interpreter gives
priority to the one in local namespace.

marks = 50 # this is a global variable


def myfunction():
marks = 70 # this is a local variable
print (marks)

myfunction()
print (marks) # prints global value

It will produce the following output −

70
50

If you try to manipulate value of a global variable from inside a function, Python

167
raises UnboundLocalError.

marks = 50 # this is a global variable


def myfunction():
marks = marks + 20
print (marks)

myfunction()
print (marks) # prints global value

It will produce the following output −

marks = marks + 20
^^^^^
UnboundLocalError: cannot access local variable 'marks' where it is not associated with a value

To modify a global variable, you can either update it with a dictionary syntax, or use
the global keyword to refer it before modifying.

var1 = 50 # this is a global variable


var2 = 60 # this is a global variable
def myfunction():
"Change values of global variables"
globals()['var1'] = globals()['var1']+10
global var2
var2 = var2 + 20

myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values

It will produce the following output −

var1: 60 var2: 80

Lastly, if you try to access a local variable in global scope, Python raises NameError as the
variable in local scope can't be accessed outside it.

var1 = 50 # this is a global variable

168
var2 = 60 # this is a global variable
def myfunction(x, y):
total = x+y
print ("Total is a local variable: ", total)

myfunction(var1, var2)
print (total) # This gives NameError

It will produce the following output −

Total is a local variable: 110


Traceback (most recent call last):
File "C:\Users\user\examples\main.py", line 9, in <module>
print (total) # This gives NameError
^^^^^
NameError: name 'total' is not defined

Python Lists
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++
and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and
separated by commas.
The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.
Example of list in Python
Here we are creating Python List using [].

Var = ["Geeks", "for", "Geeks"]

print(Var)

Output:
["Geeks", "for", "Geeks"]
Lists are the simplest containers that are an integral part of the Python language. Lists need not
be homogeneous always which makes it the most powerful tool in Python. A single list may
contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they
can be altered even after their creation.

169
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[].
Unlike Sets, a list doesn‟t need a built-in function for its creation of a list.
Note: Unlike Sets, the list may contain mutable elements.

Example 1: Creating a list in Python

# Python program to demonstrate

# Creation of List

# Creating a List

List = []

print("Blank List: ")

print(List)

# Creating a List of numbers

List = [10, 20, 14]

print("\nList of numbers: ")

print(List)

# Creating a List of strings and accessing

# using index

List = ["Geeks", "For", "Geeks"]

print("\nList Items: ")

170
print(List[0])

print(List[2])

Output
Blank List:
[]

List of numbers:
[10, 20, 14]

List Items:
Geeks
Geeks
Complexities for Creating Lists
Time Complexity: O(1)
Space Complexity: O(n)

Example 2: Creating a list with multiple distinct or duplicate elements

A list may contain duplicate values with their distinct positions and hence, multiple distinct or
duplicate values can be passed as a sequence at the time of list creation.

# Creating a List with

# the use of Numbers

# (Having duplicate values)

List = [1, 2, 4, 4, 3, 3, 3, 6, 5]

print("\nList with the use of Numbers: ")

171
print(List)

# Creating a List with

# mixed type of values

# (Having numbers and strings)

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

print("\nList with the use of Mixed Values: ")

print(List)

Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values:


[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
Accessing elements from the List
In order to access the list items refer to the index number. Use the index operator [ ] to access
an item in a list. The index must be an integer. Nested lists are accessed using nested indexing.
Example 1: Accessing elements from list

# Python program to demonstrate

# accessing of element from list

# Creating a List with

# the use of multiple values

172
List = ["Geeks", "For", "Geeks"]

# accessing a element from the

# list using index number

print("Accessing a element from the list")

print(List[0])

print(List[2])

Output
Accessing a element from the list
Geeks
Geeks
Example 2: Accessing elements from a multi-dimensional list

# Creating a Multi-Dimensional List

# (By Nesting a list inside a List)

List = [['Geeks', 'For'], ['Geeks']]

# accessing an element from the

# Multi-Dimensional List using

# index number

print("Accessing a element from a Multi-Dimensional list")

print(List[0][1])

173
print(List[1][0])

Output
Accessing a element from a Multi-Dimensional list
For
Geeks

Negative indexing

In Python, negative sequence indexes represent positions from the end of the array. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative
indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last
item, etc.

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

# accessing an element using

# negative indexing

print("Accessing element using negative indexing")

# print the last element of list

print(List[-1])

# print the third last element of list

print(List[-3])

Output
Accessing element using negative indexing
Geeks
For

174
Complexities for Accessing elements in a Lists:
Time Complexity: O(1)
Space Complexity: O(1)
Getting the size of Python list
Python len() is used to get the length of the list.

# Creating a List

List1 = []

print(len(List1))

# Creating a List of numbers

List2 = [10, 20, 14]

print(len(List2))

Output
0
3
Taking Input of a Python List
We can take the input of a list of elements as string, integer, float, etc. But the default one is a
string.
Example 1:

# Python program to take space

# separated input as a string

# split and store it to a list

# and print the string list

175
# input the list as string

string = input("Enter elements (Space-Separated): ")

# split the strings and store it to a list

lst = string.split()

print('The list is:', lst) # printing the list

Output:
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
Example 2:

# input size of the list

n = int(input("Enter the size of list : "))

# store integers in a list using map,

# split and strip functions

lst = list(map(int, input("Enter the integer\

elements:").strip().split()))[:n]

# printing the list

print('The list is:', lst)

Output:
Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]

176
Adding Elements to a Python List

Method 1: Using append() method

Elements can be added to the List by using the built-in append() function. Only one element at
a time can be added to the list by using the append() method, for the addition of multiple
elements with the append() method, loops are used. Tuples can also be added to the list with
the use of the append method because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of the append() method.

# Python program to demonstrate

# Addition of elements in a List

# Creating a List

List = []

print("Initial blank List: ")

print(List)

# Addition of Elements

# in the List

List.append(1)

List.append(2)

List.append(4)

print("\nList after Addition of Three elements: ")

print(List)

177
# Adding elements to the List

# using Iterator

for i in range(1, 4):

List.append(i)

print("\nList after Addition of elements from 1-3: ")

print(List)

# Adding Tuples to the List

List.append((5, 6))

print("\nList after Addition of a Tuple: ")

print(List)

# Addition of List to a List

List2 = ['For', 'Geeks']

List.append(List2)

print("\nList after Addition of a List: ")

print(List)

Output
Initial blank List:
[]

List after Addition of Three elements:

178
[1, 2, 4]

List after Addition of elements from 1-3:


[1, 2, 4, 1, 2, 3]

List after Addition of a Tuple:


[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List:


[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]
\
omplexities for Adding elements in a Lists(append() method):
Time Complexity: O(1)
Space Complexity: O(1)

Method 2: Using insert() method

append() method only works for the addition of elements at the end of the List, for the addition
of elements at the desired position, insert() method is used. Unlike append() which takes only
one argument, the insert() method requires two arguments(position, value).

# Python program to demonstrate

# Addition of elements in a List

# Creating a List

List = [1,2,3,4]

print("Initial List: ")

print(List)

# Addition of Element at

179
# specific Position

# (using Insert Method)

List.insert(3, 12)

List.insert(0, 'Geeks')

print("\nList after performing Insert Operation: ")

print(List)

Output
Initial List:
[1, 2, 3, 4]

List after performing Insert Operation:


['Geeks', 1, 2, 3, 12, 4]
Complexities for Adding elements in a Lists(insert() method):
Time Complexity: O(n)
Space Complexity: O(1)

Method 3: Using extend() method

Other than append() and insert() methods, there‟s one more method for the Addition of
elements, extend(), this method is used to add multiple elements at the same time at the end of
the list.
Note: append() and extend() methods can only add elements at the end.

# Python program to demonstrate

# Addition of elements in a List

# Creating a List

180
List = [1, 2, 3, 4]

print("Initial List: ")

print(List)

# Addition of multiple elements

# to the List at the end

# (using Extend Method)

List.extend([8, 'Geeks', 'Always'])

print("\nList after performing Extend Operation: ")

print(List)

Output
Initial List:
[1, 2, 3, 4]

List after performing Extend Operation:


[1, 2, 3, 4, 8, 'Geeks', 'Always']
Complexities for Adding elements in a Lists(extend() method):
Time Complexity: O(n)
Space Complexity: O(1)
Reversing a List
Method 1: A list can be reversed by using the reverse() method in Python.

# Reversing a list

mylist = [1, 2, 3, 4, 5, 'Geek', 'Python']

181
mylist.reverse()

print(mylist)

Output
['Python', 'Geek', 5, 4, 3, 2, 1]
Method 2: Using the reversed() function:
The reversed() function returns a reverse iterator, which can be converted to a list using the
list() function.

my_list = [1, 2, 3, 4, 5]

reversed_list = list(reversed(my_list))

print(reversed_list)

Output
[5, 4, 3, 2, 1]
Removing Elements from the List

Method 1: Using remove() method

Elements can be removed from the List by using the built-in remove() function but an Error
arises if the element doesn‟t exist in the list. Remove() method only removes one element at a
time, to remove a range of elements, the iterator is used. The remove() method removes the
specified item.
Note: Remove method in List will only remove the first occurrence of the searched element.
Example 1:

# Python program to demonstrate

# Removal of elements in a List

182
# Creating a List

List = [1, 2, 3, 4, 5, 6,

7, 8, 9, 10, 11, 12]

print("Initial List: ")

print(List)

# Removing elements from List

# using Remove() method

List.remove(5)

List.remove(6)

print("\nList after Removal of two elements: ")

print(List)

Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal of two elements:


[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
Example 2:

# Creating a List

List = [1, 2, 3, 4, 5, 6,

183
7, 8, 9, 10, 11, 12]

# Removing elements from List

# using iterator method

for i in range(1, 5):

List.remove(i)

print("\nList after Removing a range of elements: ")

print(List)

Output
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]
Complexities for Deleting elements in a Lists(remove() method):
Time Complexity: O(n)
Space Complexity: O(1)

Method 2: Using pop() method

pop() function can also be used to remove and return an element from the list, but by default it
removes only the last element of the list, to remove an element from a specific position of the
List, the index of the element is passed as an argument to the pop() method.

List = [1, 2, 3, 4, 5]

# Removing element from the

# Set using the pop() method

List.pop()

184
print("\nList after popping an element: ")

print(List)

# Removing element at a

# specific location from the

# Set using the pop() method

List.pop(2)

print("\nList after popping a specific element: ")

print(List)

Output
List after popping an element:
[1, 2, 3, 4]

List after popping a specific element:


[1, 2, 4]
Complexities for Deleting elements in a Lists(pop() method):
Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for removing the first
and middle elements)
Space Complexity: O(1)
Slicing of a List
We can get substrings and sublists using a slice. In Python List, there are multiple ways to
print the whole list with all the elements, but to print a specific range of elements from the list,
we use the Slice operation.
Slice operation is performed on Lists with the use of a colon(:).
To print elements from beginning to a range use:
[: Index]
To print elements from end-use:
[:-Index]
To print elements from a specific Index till the end use

185
[Index:]
To print the whole list in reverse order, use
[::-1]
Note – To print elements of List from rear-end, use Negative Indexes.

UNDERSTANDING SLICING OF LISTS:


 pr[0] accesses the first item, 2.
 pr[-4] accesses the fourth item from the end, 5.
 pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
 pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.
 pr[2:4] accesses [5, 7], a list of items from third to fifth.
 pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.

# Python program to demonstrate

# Removal of elements in a List

# Creating a List

List = ['G', 'E', 'E', 'K', 'S', 'F',

'O', 'R', 'G', 'E', 'E', 'K', 'S']

186
print("Initial List: ")

print(List)

# Print elements of a range

# using Slice operation

Sliced_List = List[3:8]

print("\nSlicing elements in a range 3-8: ")

print(Sliced_List)

# Print elements from a

# pre-defined point to end

Sliced_List = List[5:]

print("\nElements sliced from 5th "

"element till the end: ")

print(Sliced_List)

# Printing elements from

# beginning till end

Sliced_List = List[:]

print("\nPrinting all elements using slice operation: ")

print(Sliced_List)

Output

187
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Slicing elements in a range 3-8:


['K', 'S', 'F', 'O', 'R']

Elements sliced from 5th element till the end:


['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Printing all elements using slice operation:


['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Negative index List slicing

# Creating a List

List = ['G', 'E', 'E', 'K', 'S', 'F',

'O', 'R', 'G', 'E', 'E', 'K', 'S']

print("Initial List: ")

print(List)

# Print elements from beginning

# to a pre-defined point using Slice

Sliced_List = List[:-6]

print("\nElements sliced till 6th element from last: ")

188
print(Sliced_List)

# Print elements of a range

# using negative index List slicing

Sliced_List = List[-6:-1]

print("\nElements sliced from index -6 to -1")

print(Sliced_List)

# Printing elements in reverse

# using Slice operation

Sliced_List = List[::-1]

print("\nPrinting List in reverse: ")

print(Sliced_List)

Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Elements sliced till 6th element from last:


['G', 'E', 'E', 'K', 'S', 'F', 'O']

Elements sliced from index -6 to -1


['R', 'G', 'E', 'E', 'K']

Printing List in reverse:


['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G']

189
List Comprehension
Python List comprehensions are used for creating new lists from other iterables like tuples,
strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression,
which is executed for each element along with the for loop to iterate over each element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Example:

# Python program to demonstrate list

# comprehension in Python

# below list contains square of all

# odd numbers from range 1 to 10

odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]

print(odd_square)

Output
[1, 9, 25, 49, 81]
For better understanding, the above code is similar to as follows:

# for understanding, above generation is same as,

odd_square = []

for x in range(1, 11):

if x % 2 == 1:

odd_square.append(x**2)

190
print(odd_square)

Output
[1, 9, 25, 49, 81]
Basic Example on Python List
To Practice the basic list operation, please read this article – Python List of program
List Methods
Function Description

Append() Add an element to the end of the list

Extend() Add all elements of a list to another list

Insert() Insert an item at the defined index

Remove() Removes an item from the list

Clear() Removes all items from the list

Index() Returns the index of the first matched item

Count() Returns the count of the number of items passed as an argument

Sort() Sort items in a list in ascending order

Reverse() Reverse the order of items in the list

copy() Returns a copy of the list

191
Function Description

Removes and returns the item at the specified index. If no index is provided, it
pop()
removes and returns the last item.

To know more refer to this article – Python List methods


The operations mentioned above modify the list Itself.

Built-in functions with List

Function Description

apply a particular function passed in its argument to all of the list elements
reduce()
stores the intermediate result and only returns the final summation value

sum() Sums up the numbers in the list

Returns an integer representing the Unicode code point of the given Unicode
ord()
character

cmp() This function returns 1 if the first list is “greater” than the second list

max() return maximum element of a given list

min() return minimum element of a given list

all() Returns true if all element is true or if the list is empty

any() return true if any element of the list is true. if the list is empty, return false

len() Returns length of the list or size of the list

192
Function Description

enumerate() Returns enumerate object of the list

apply a particular function passed in its argument to all of the list elements
accumulate()
returns a list containing the intermediate results

filter() tests if each element of a list is true or not

returns a list of the results after applying the given function to each item of a
map()
given iterable

This function can have any number of arguments but only one expression,
lambda()
which is evaluated and returned.

Tuples in Python
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to
a Python list in terms of indexing, nested objects, and repetition but the main difference between
both is Python tuple is immutable, unlike the Python list which is mutable.
Creating Python Tuples
There are various ways by which you can create a tuple in Python. They are as follows:
 Using round brackets
 With one item
 Tuple Constructor
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.

var = ("Geeks", "for", "Geeks")

print(var)

Output:
('Geeks', 'for', 'Geeks')
Create a Tuple With One Item
Python 3.11 provides us with another way to create a Tuple.

193
values : tuple[int | str, ...] = (1,2,4,"Geek")

print(values)

Output:
Here, in the above snippet we are considering a variable called values which holds a tuple that
consists of either int or str, the „…‟ means that the tuple will hold more than one int or str.
(1, 2, 4, 'Geek')
Note: In case your generating a tuple with a single element, make sure to add a comma after the
element. Let us see an example of the same.

mytuple = ("Geeks",)

print(type(mytuple))

#NOT a tuple

mytuple = ("Geeks")

print(type(mytuple))

Output:
<class 'tuple'>
<class 'str'>
Tuple Constructor in Python
To create a tuple with a Tuple constructor, we will pass the elements as its parameters.

tuple_constructor = tuple(("dsa", "developement", "deep learning"))

print(tuple_constructor)

Output :
('dsa', 'developement', 'deep learning')

194
What is Immutable in Tuples?
Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered
and allow duplicate values. Some Characteristics of Tuples in Python.
 We can find items in a tuple since finding any item does not make changes in the tuple.
 One cannot add items to a tuple once it is created.
 Tuples cannot be appended or extended.
 We cannot remove items from a tuple once it is created.
Let us see this with an example.

mytuple = (1, 2, 3, 4, 5)

# tuples are indexed

print(mytuple[1])

print(mytuple[4])

# tuples contain duplicate elements

mytuple = (1, 2, 3, 4, 2, 3)

print(mytuple)

# adding an element

mytuple[1] = 100

print(mytuple)

Output:
Python tuples are ordered and we can access their elements using their index values. They are
also immutable, i.e., we cannot add, remove and change the elements once declared in the tuple,
so when we tried to add an element at index 1, it generated the error.
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 11, in
tuple1[1] = 100
TypeError: 'tuple' object does not support item assignment

195
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a tuple.
 Using a positive index
 Using a negative index
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.

var = ("Geeks", "for", "Geeks")

print("Value in Var[0] = ", var[0])

print("Value in Var[1] = ", var[1])

print("Value in Var[2] = ", var[2])

Output:
Value in Var[0] = Geeks
Value in Var[1] = for
Value in Var[2] = Geeks
Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python, and here we will
use the negative index within [].

var = (1, 2, 3)

print("Value in Var[-1] = ", var[-1])

print("Value in Var[-2] = ", var[-2])

print("Value in Var[-3] = ", var[-3])

Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1

Different Operations Related to Tuples


Below are the different operations related to tuples in Python:

196
 Concatenation
 Nesting
 Repetition
 Slicing
 Deleting
 Finding the length
 Multiple Data Types with tuples
 Conversion of lists to tuples
 Tuples in a Loop

Concatenation of Python Tuples


To Concatenation of Python Tuples, we will use plus operators(+).
Python3

# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)

tuple2 = ('python', 'geek')

# Concatenating above two

print(tuple1 + tuple2)

Output:
(0, 1, 2, 3, 'python', 'geek')
Nesting of Python Tuples
A nested tuple in Python means a tuple inside another tuple.
Python3

# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)

tuple2 = ('python', 'geek')

tuple3 = (tuple1, tuple2)

197
print(tuple3)

Output :
((0, 1, 2, 3), ('python', 'geek'))
Repetition Python Tuples
We can create a tuple of multiple same elements from a single element in that tuple.
Python3

# Code to create a tuple with repetition

tuple3 = ('python',)*3

print(tuple3)

Output:
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string
„pythonpythonpython‟.
Slicing Tuples in Python
Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.
Python3

# code to test slicing

tuple1 = (0 ,1, 2, 3)

print(tuple1[1:])

print(tuple1[::-1])

print(tuple1[2:4])

Output:
In this example, we sliced the tuple from index 1 to the last element. In the second print
statement, we printed the tuple using reverse indexing. And in the third print statement, we
printed the elements from index 2 to 4.
(1, 2, 3)

198
(3, 2, 1, 0)
(2, 3)
Note: In Python slicing, the end index provided is not included.
Deleting a Tuple in Python
In this example, we are deleting a tuple using „del‟ keyword. The output will be in the form of
error because after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using
Del keyword.
Python3

# Code for deleting a tuple

tuple3 = ( 0, 1)

del tuple3

print(tuple3)

Output:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined
Finding the Length of a Python Tuple
To find the length of a tuple, we can use Python‟s len() function and pass the tuple as the
parameter.
Python3

# Code for printing the length of a tuple

tuple2 = ('python', 'geek')

print(len(tuple2))

Output:
2
Multiple Data Types With Tuple
Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple
datatypes.

199
Python3

# tuple with different datatypes

tuple_obj = ("immutable",True,23)

print(tuple_obj)

Output :
('immutable', True, 23)
Converting a List to a Tuple
We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as
its parameters.
Python3

# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]

print(tuple(list1))

# string 'python'

print(tuple('python'))

Output:
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are
taken as elements), and converts them to a tuple.
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Tuples in a Loop
We can also create a tuple with a single element in it using loops.

200
Python3

# python code for creating tuples in a loop

tup = ('geek',)

# Number of time loop runs

n=5

for i in range(int(n)):

tup = (tup,)

print(tup)

Output:
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),)

Python Dictionary
A dictionary in Python is a collection of key values, used to store data values like a map,
which, unlike other data types holds Key-value only a single value as an element.
Python Dictionary Syntax
dict_var = {key1 : value1, key2 : value2, …..}
Example of Dictionary in Python
The dictionary holds the A dictionarykey: value pair. Key-value is provided in the dictionary to
make it more optimized.
The code defines a Python dictionary named Dict with three key-value pairs. Each key is an
integer, and each value is a string. The code then prints the contents of the dictionary.

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

201
print(Dict)

Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Creating a Dictionary in Python


In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by „comma‟. Dictionary holds pairs of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any data type
and can be duplicated, whereas keys can‟t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
The code demonstrates creating dictionaries with different types of keys. The first dictionary
uses integer keys, and the second dictionary uses a mix of string and integer keys with
corresponding values. This showcases the flexibility of Python dictionaries in handling various
data types as keys.

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

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

print(Dict)

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

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

print(Dict)

Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}

Dictionary can also be created by the built-in function dict(). An empty dictionary can be created
by just placing to curly braces{}.
Different ways to create Python Dictionary

202
The code demonstrates different ways to create dictionaries in Python. It first creates an empty
dictionary, then shows how to create dictionaries using the dict() constructor with key-value
pairs specified within curly braces and as a list of tuples.

Dict = {}

print("Empty Dictionary: ")

print(Dict)

Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})

print("\nDictionary with the use of dict(): ")

print(Dict)

Dict = dict([(1, 'Geeks'), (2, 'For')])

print("\nDictionary with each item as a pair: ")

print(Dict)

Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}

Complexities for Creating a Dictionary


Time complexity: O(len(dict))
Space complexity: O(n)

203
Nested Dictionary

Example: The code defines a nested dictionary named ‘Dict' with multiple levels of key-value
pairs. It includes a top-level dictionary with keys 1, 2, and 3. The value associated with key 3 is
another dictionary with keys „A,‟ „B,‟ and „C.‟ This showcases how Python dictionaries can be
nested to create hierarchical data structures.

Dict = {1: 'Geeks', 2: 'For',

3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

print(Dict)

Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

Adding elements to a Dictionary


Addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = „Value‟. Updating an existing
value in a Dictionary can be done by using the built-in update() method. Nested key values can
also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise a
new Key with the value is added to the Dictionary.
Example: Add Items to a Python Dictionary with Different DataTypes

204
The code starts with an empty dictionary and then adds key-value pairs to it. It demonstrates
adding elements with various data types, updating a key‟s value, and even nesting dictionaries
within the main dictionary. The code shows how to manipulate dictionaries in Python.
 Python3

Dict = {}

print("Empty Dictionary: ")

print(Dict)

Dict[0] = 'Geeks'

Dict[2] = 'For'

Dict[3] = 1

print("\nDictionary after adding 3 elements: ")

print(Dict)

Dict['Value_set'] = 2, 3, 4

print("\nDictionary after adding 3 elements: ")

print(Dict)

Dict[2] = 'Welcome'

print("\nUpdated key value: ")

print(Dict)

Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}

print("\nAdding a Nested Key: ")

205
print(Dict)

Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Geeks'}}}

Complexities for Adding elements in a Dictionary:


Time complexity: O(1)/O(n)
Space complexity: O(1)
Accessing elements of a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.
Access a Value in Python Dictionary
The code demonstrates how to access elements in a dictionary using keys. It accesses and prints
the values associated with the keys „name‟ and 1, showcasing that keys can be of different data
types (string and integer).
 Python3

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print("Accessing a element using key:")

print(Dict['name'])

print("Accessing a element using key:")

print(Dict[1])

Output:
Accessing a element using key:
For
206
Accessing a element using key:
Geeks

There is also a method called get() that will also help in accessing the element from a
dictionary.This method accepts key as argument and returns the value.
Complexities for Accessing elements in a Dictionary:
Time complexity: O(1)
Space complexity: O(1)
Example: Access a Value in Dictionary using get() in Python
The code demonstrates accessing a dictionary element using the get() method. It retrieves and
prints the value associated with the key 3 in the dictionary ‘Dict'. This method provides a safe
way to access dictionary values, avoiding KeyError if the key doesn‟t exist.
 Python3

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print("Accessing a element using get:")

print(Dict.get(3))

Output:
Accessing a element using get:
Geeks

Accessing an element of a nested Dictionary


In order to access the value of any key in the nested dictionary, use indexing [] syntax.
Example: The code works with nested dictionaries. It first accesses and prints the entire nested
dictionary associated with the key ‘Dict1’. Then, it accesses and prints a specific value by
navigating through the nested dictionaries. Finally, it retrieves and prints the value associated
with the key ‘Name’ within the nested dictionary under ‘Dict2’.
 Python3

Dict = {'Dict1': {1: 'Geeks'},

'Dict2': {'Name': 'For'}}

207
print(Dict['Dict1'])

print(Dict['Dict1'][1])

print(Dict['Dict2']['Name'])

Output:
{1: 'Geeks'}
Geeks
For

Deleting Elements using del Keyword


The items of the dictionary can be deleted by using the del keyword as given below.
Example: The code defines a dictionary, prints its original content, and then uses
the ‘del' statement to delete the element associated with key 1. After deletion, it prints the
updated dictionary, showing that the specified element has been removed.

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print("Dictionary =")

print(Dict)

del(Dict[1])

print("Data after deletion Dictionary=")

print(Dict)

Output

Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'}


Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}

208
Dictionary methods

Method Description

dic.clear() Remove all the elements from the dictionary

dict.copy() Returns a copy of the dictionary

dict.get(key, default = “None”) Returns the value of specified key

Returns a list containing a tuple for each key


dict.items()
value pair

dict.keys() Returns a list containing dictionary‟s keys

Updates dictionary with specified key-value


dict.update(dict2)
pairs

dict.values() Returns a list of all the values of dictionary

pop() Remove the element with specified key

popItem() Removes the last inserted key-value pair

set the key to the default value if the key is


dict.setdefault(key,default= “None”)
not specified in the dictionary

returns true if the dictionary contains the


dict.has_key(key)
specified key.

209
Method Description

used to get the value specified for the passed


dict.get(key, default = “None”)
key.

Multiple Dictionary Operations in Python


The code begins with a dictionary ‘dict1' and creates a copy ‘dict2'. It then demonstrates several
dictionary operations: clearing ‘dict1', accessing values, retrieving key-value pairs and keys,
removing specific key-value pairs, updating a value, and retrieving values. These operations
showcase how to work with dictionaries in Python.

dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}

dict2 = dict1.copy()

print(dict2)

dict1.clear()

print(dict1)

print(dict2.get(1))

print(dict2.items())

print(dict2.keys())

dict2.pop(4)

print(dict2)

dict2.popitem()

print(dict2)

210
dict2.update({3: "Scala"})

print(dict2)

print(dict2.values())

Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])

Sets in Python

A Set in Python programming is an unordered collection data type that is iterable, mutable and
has no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on a data
structure known as a hash table. Since sets are unordered, we cannot access items using
indexes as we do in lists.
Example of Python Sets

 Python3

var = {"Geeks", "for", "Geeks"}

type(var)

Output:
set
Time Complexity: O(1)
Auxiliary Space: O(1)

211
Type Casting with Python Set method

The Python set() method is used for type casting.

 Python3

# typecasting list to set

myset = set(["a", "b", "c"])

print(myset)

# Adding element to the set

myset.add("d")

print(myset)

Output:
Python set is an unordered datatype, which means we cannot know in which order the elements
of the set are stored.
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Time Complexity: O(n)
Auxiliary Space: O(n)

Check unique and Immutable with Python Set

Python sets cannot have a duplicate value and once it is created we cannot change its value.

 Python3

# Python program to demonstrate that

212
# a set cannot have duplicate values

# and we cannot change its items

# a set cannot have duplicate values

myset = {"Geeks", "for", "Geeks"}

print(myset)

# values of a set cannot be changed

myset[1] = "Hello"

print(myset)

Output:
The first code explains that the set cannot have a duplicate value. Every item in it is a unique
value.
The second code generates an error because we cannot assign or change a value once the set is
created. We can only add or delete items in the set.
{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment

Heterogeneous Element with Python Set

Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string,
integer, boolean, etc datatypes.

 Python3

213
# Python example demonstrate that a set

# can store heterogeneous elements

myset = {"Geeks", "for", 10, 52.7, True}

print(myset)

Output:
{True, 10, 'Geeks', 52.7, 'for'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Python Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied. It can be
done with frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain the
same after creation.
If no parameters are passed, it returns an empty frozenset.

 Python

# Python program to demonstrate differences

# between normal and frozen set

# Same as {"a", "b","c"}

normal_set = set(["a", "b","c"])

214
print("Normal Set")

print(normal_set)

# A frozen set

frozen_set = frozenset(["e", "f", "g"])

print("\nFrozen Set")

print(frozen_set)

# Uncommenting below line would cause error as

# we are trying to add element to a frozen set

# frozen_set.add("h")

Output:
Normal Set
{'a', 'c', 'b'}

Frozen Set
{'e', 'g', 'f'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Internal working of Set
This is based on a data structure known as a hash table. If Multiple values are present at the
same index position, then the value is appended to that index position, to form a Linked List.
In, Python Sets are implemented using a dictionary with dummy variables, where key beings
the members set with greater optimizations to the time complexity.
Set Implementation:

215
Sets with Numerous operations on a single HashTable:

Methods for Sets

Adding elements to Python Sets

216
Insertion in the set is done through the set.add() function, where an appropriate record value is
created to store in the hash table. Same as checking for an item, i.e., O(1) on average.
However, in worst case it can become O(n).
 Python3

# A Python program to

# demonstrate adding elements

# in a set

# Creating a Set

people = {"Jay", "Idrish", "Archi"}

print("People:", end = " ")

print(people)

# This will add Daxit

# in the set

people.add("Daxit")

# Adding elements to the

# set using iterator

217
for i in range(1, 6):

people.add(i)

print("\nSet after adding element:", end = " ")

print(people)

Output:
People: {'Idrish', 'Archi', 'Jay'}

Set after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi', 'Jay', 'Daxit'}


Time Complexity: O(n)
Auxiliary Space: O(n)

Union operation on Python Sets

Two sets can be merged using union() function or | operator. Both Hash Table values are
accessed and traversed with merge operation perform on them to combine the elements, at the
same time duplicates are removed. The Time Complexity of this is O(len(s1) + len(s2)) where
s1 and s2 are two sets whose union needs to be done.
 Python3

# Python Program to

# demonstrate union of

# two sets

people = {"Jay", "Idrish", "Archil"}

218
vampires = {"Karan", "Arjun"}

dracula = {"Deepanshu", "Raju"}

# Union using union()

# function

population = people.union(vampires)

print("Union using union() function")

print(population)

# Union using "|"

# operator

population = people|dracula

print("\nUnion using '|' operator")

print(population)

Output:
Union using union() function
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}

219
Union using '|' operator
{'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}
Time Complexity: O(n)
Auxiliary Space: O(n)

Intersection operation on Python Sets

This can be done through intersection() or & operator. Common Elements are selected. They
are similar to iteration over the Hash lists and combining the same values on both the Table.
Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union
needs to be done.

 Python3

# Python program to

# demonstrate intersection

# of two sets

set1 = set()

set2 = set()

for i in range(5):

set1.add(i)

for i in range(3,9):

220
set2.add(i)

# Intersection using

# intersection() function

set3 = set1.intersection(set2)

print("Intersection using intersection() function")

print(set3)

# Intersection using

# "&" operator

set3 = set1 & set2

print("\nIntersection using '&' operator")

print(set3)

Output:
Intersection using intersection() function
{3, 4}

Intersection using '&' operator


{3, 4}
Time Complexity: O(n)
Auxiliary Space: O(n)

Finding Differences of Sets in Python

To find differences between sets. Similar to finding differences in the linked list. This is done
through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1))

 Python3
221
# Python program to

# demonstrate difference

# of two sets

set1 = set()

set2 = set()

for i in range(5):

set1.add(i)

for i in range(3,9):

set2.add(i)

# Difference of two sets

# using difference() function

set3 = set1.difference(set2)

print(" Difference of two sets using difference() function")

222
print(set3)

# Difference of two sets

# using '-' operator

set3 = set1 - set2

print("\nDifference of two sets using '-' operator")

print(set3)

Output:
Difference of two sets using difference() function
{0, 1, 2}

Difference of two sets using '-' operator


{0, 1, 2}
Time Complexity: O(n)
Auxiliary Space: O(n)

Clearing Python Sets

Set Clear() method empties the whole set inplace.

 Python3

# Python program to

# demonstrate clearing

223
# of set

set1 = {1,2,3,4,5,6}

print("Initial set")

print(set1)

# This method will remove

# all the elements of the set

set1.clear()

print("\nSet after using clear() function")

print(set1)

Output:
Initial set
{1, 2, 3, 4, 5, 6}

Set after using clear() function


set()
Time Complexity: O(n)
Auxiliary Space: O(n)
However, there are two major pitfalls in Python sets:
1. The set doesn‟t maintain elements in any particular order.
2. Only instances of immutable types can be added to a Python set.
Time complexity of Sets
Operation Average case Worst Case notes

224
Operation Average case Worst Case notes

x in s O(1) O(n)

Union s|t O(len(s)+len(t))

replace “min”
O(min(len(s),
Intersection s&t O(len(s) * len(t)) with “max” if t is
len(t))
not a set

Multiple intersection (n-1)*O(l) where l is


s1&s2&..&sn max(len(s1),..,len(sn))

Difference s-t O(len(s))

Operators for Sets


Sets and frozen sets support the following operators:

Operators Notes

key in s containment check

key not in s non-containment check

s1 == s2 s1 is equivalent to s2

s1 != s2 s1 is not equivalent to s2

s1 <= s2 s1 is subset of s2

s1 < s2 s1 is proper subset of s2

225
Operators Notes

s1 >= s2 s1 is superset of s2

s1 > s2 s1 is proper superset of s2

s1 | s2 the union of s1 and s2

s1 & s2 the intersection of s1 and s2

s1 – s2 the set of elements in s1 but not s2

s1 ˆ s2 the set of elements in precisely one of s1 or s2

Python Sequence Types

Some basic sequence type classes in python are, list, tuple, range. There are some additional
sequence type objects, these are binary data and text string.

Some common operations for the sequence type object can work on both mutable and immutable
sequences. Some of the operations are as follows −

Sr.No. Operation/Functions & Description

1 x in seq
True, when x is found in the sequence seq, otherwise False

2 x not in seq
False, when x is found in the sequence seq, otherwise True

3 x+y
Concatenate two sequences x and y

226
4 x * n or n * x
Add sequence x with itself n times

5 seq[i]
ith item of the sequence.

6 seq[i:j]
Slice sequence from index i to j

7 seq[i:j:k]
Slice sequence from index i to j with step k

8 len(seq)
Length or number of elements in the sequence

9 min(seq)
Minimum element in the sequence

10 max(seq)
Maximum element in the sequence

11 seq.index(x[, i[, j]])


Index of the first occurrence of x (in the index range i and j)

12 seq.count(x)
Count total number of elements in the sequence

13 seq.append(x)
Add x at the end of the sequence

14 seq.clear()
Clear the contents of the sequence

15 seq.insert(i, x)
Insert x at the position i

16 seq.pop([i])
Return the item at position i, and also remove it from sequence. Default is last element.

227
17 seq.remove(x)
Remove first occurrence of item x

18 seq.reverse()
Reverse the list

Example Code

myList1 = [10, 20, 30, 40, 50]


myList2 = [56, 42, 79, 42, 85, 96, 23]

if 30 in myList1:
print('30 is present')

if 120 not in myList1:


print('120 is not present')

print(myList1 + myList2) #Concatinate lists


print(myList1 * 3) #Add myList1 three times with itself
print(max(myList2))
print(myList2.count(42)) #42 has two times in the list

print(myList2[2:7])
print(myList2[2:7:2])

myList1.append(60)
print(myList1)

myList2.insert(5, 17)
print(myList2)

myList2.pop(3)
print(myList2)
myList1.reverse()
print(myList1)

myList1.clear()
print(myList1)
Output
30 is present
120 is not present
[10, 20, 30, 40, 50, 56, 42, 79, 42, 85, 96, 23]
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50]

228
96
2
[79, 42, 85, 96, 23]
[79, 85, 23]
[10, 20, 30, 40, 50, 60]
[56, 42, 79, 42, 85, 17, 96, 23]
[56, 42, 79, 85, 17, 96, 23]
[60, 50, 40, 30, 20, 10]
[]

Comprehensions in Python
Comprehensions
as lists,
types ofsets, in Python
comprehension:
dictionaries, provide
etc.) usingus with a short
previously and concise
defined wayPython
sequences. to construct newthe
supports sequences
following(such
4
 List Comprehensions
 Dictionary Comprehensions
 Set Comprehensions
 Generator Comprehensions
List Comprehensions
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of list comprehension:
Syntax: output_list = [output_exp for var in input_list if (var satisfies this condition)]
Note that list comprehension may or may not contain an if condition. List comprehensions can
contain multiple
Example 1: Generating an Even list WITHOUT using List comprehensions
Suppose we want to create an output list that contains only the even numbers which are present
in the input list. Let‟s see how to do this using loops, list comprehension, and list
comprehension, and decide which method suits you better.
 Python3

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

output_list = []

for var in input_list:

229
if var % 2 == 0:

output_list.append(var)

print("Output List using for loop:", output_list)

Output:
Output List using for loop: [2, 4, 4, 6]
Example 2: Generating Even list using List comprehensions
Here we use the list comprehensions in Python. It creates a new list named list_using_comp by
iterating through each element var in the input_list. Elements are included in the new list only if
they satisfy the condition, which checks if the element is even. As a result, the output list will
contain all even numbers.
 Python3

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

list_using_comp = [var for var in input_list if var % 2 == 0]

print("Output List using list comprehensions:",

list_using_comp)

Output:
Output List using list comprehensions: [2, 4, 4, 6]
Example 1: Squaring Number WITHOUT using List comprehensions
Suppose we want to create an output list which contains squares of all the numbers from 1 to 9.
Let‟s see how to do this using for loops and list comprehension.
 Python3

230
output_list = []

for var in range(1, 10):

output_list.append(var ** 2)

print("Output List using for loop:", output_list)

Output:
Output List using for loop: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Example 2: Squaring Number using List comprehensions
In This we use list comprehension to generate a new list. It iterates through the numbers in the
range from 1 to 9 (inclusive). For each number var, it calculates the square of the number using
the expression and adds the result to the new list. The printed output will contain the squares of
numbers from 1 to 9.
 Python3

list_using_comp = [var**2 for var in range(1, 10)]

print("Output List using list comprehension:",

list_using_comp)

Output:
Output List using list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Dictionary Comprehensions
Extending the idea of list comprehensions, we can also create a dictionary using dictionary
comprehensions. The basic structure of a dictionary comprehension looks like below.
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}
Example 1: Generating odd number with their cube values without using dictionary
comprehension

231
Suppose we want to create an output dictionary which contains only the odd numbers that are
present in the input list as keys and their cubes as values. Let‟s see how to do this using for loops
and dictionary comprehension.
 Python3

input_list = [1, 2, 3, 4, 5, 6, 7]

output_dict = {}

for var in input_list:

if var % 2 != 0:

output_dict[var] = var**3

print("Output Dictionary using for loop:",output_dict )

Output:
Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}
Example 2: Generating odd number with their cube values with using dictionary
comprehension
We are using dictionary comprehension in Python. It initializes an list containing numbers from
1 to 7. It then constructs a new dictionary using dictionary comprehension. For each odd
number var in the list, it calculates the cube of the number and assigns the result as the value to
the key var in the dictionary.
 Python3

input_list = [1,2,3,4,5,6,7]

232
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}

print("Output Dictionary using dictionary comprehensions:",dict_using_comp)

Output:
Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7: 343}
Example 1: Mapping states with their capitals without Using dictionary comprehension
Given two lists containing the names of states and their corresponding capitals, construct a
dictionary which maps the states with their respective capitals. Let‟s see how to do this using for
loops and dictionary comprehension.
 Python3

state = ['Gujarat', 'Maharashtra', 'Rajasthan']

capital = ['Gandhinagar', 'Mumbai', 'Jaipur']

output_dict = {}

for (key, value) in zip(state, capital):

output_dict[key] = value

print("Output Dictionary using for loop:",output_dict)

Output:

233
Output Dictionary using for loop: {'Gujarat': 'Gandhinagar',
'Maharashtra': 'Mumbai',
'Rajasthan': 'Jaipur'}
Example 2: Mapping states with their capitals with using dictionary comprehension
Here we will use dictionary comprehension to initializes two lists, state and capital, containing
corresponding pairs of states and their capitals. It iterates through the pairs
of state and capital using the zip() function, and for each pair, it creates a key-value pair in the
dictionary. The key is taken from the state list, and the value is taken from the capital list.
Finally, the printed output will contain the mapping of states to their capitals.
 Python3

state = ['Gujarat', 'Maharashtra', 'Rajasthan']

capital = ['Gandhinagar', 'Mumbai', 'Jaipur']

dict_using_comp = {key:value for (key, value) in zip(state, capital)}

print("Output Dictionary using dictionary comprehensions:",

dict_using_comp)

Output:
Output Dictionary using dictionary comprehensions: {'Rajasthan': 'Jaipur',
'Maharashtra': 'Mumbai',
'Gujarat': 'Gandhinagar'}
Set Comprehensions
Set comprehensions are pretty similar to list comprehensions. The only difference between them
is that set comprehensions use curly brackets { }
Let‟s look at the following example to understand set comprehensions.
Example 1 : Checking Even number Without using set comprehension
Suppose we want to create an output set which contains only the even numbers that are present
in the input list. Note that set will discard all the duplicate values. Let‟s see how we can do this
using for loops and set comprehension.
 Python3

234
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

output_set = set()

for var in input_list:

if var % 2 == 0:

output_set.add(var)

print("Output Set using for loop:", output_set)

Output:
Output Set using for loop: {2, 4, 6}
Example 2: Checking Even number using set comprehension
We will use set comprehension to initializes a list with integer values. The code then creates a
new set using set comprehension. It iterates through the elements of the input_list, and for each
element, it checks whether it‟s even. If the condition is met, the element is added to the set. The
printed output which will contain unique even numbers from the list.
 Python3

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

set_using_comp = {var for var in input_list if var % 2 == 0}

235
print("Output Set using set comprehensions:",

set_using_comp)

Output:
Output Set using set comprehensions: {2, 4, 6}
Generator Comprehensions
Generator Comprehensions are very similar to list comprehensions. One difference between
them is that generator comprehensions use circular brackets whereas list comprehensions use
square brackets. The major difference between them is that generators don‟t allocate memory for
the whole list. Instead, they generate each value one by one which is why they are memory
efficient. Let‟s look at the following example to understand generator comprehension:
 Python3

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

output_gen = (var for var in input_list if var % 2 == 0)

print("Output values using generator comprehensions:", end = ' ')

for var in output_gen:

print(var, end = ' ')

Output:
Output values using generator comprehensions: 2 4 4 6

236

You might also like