Python Unit 3
Python Unit 3
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.
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.
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
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()
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
−
The function calling mechanism of Python differs from that of C and C++. There are two main
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")
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 −
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.
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.
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)
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)
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
# 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
Name: Naveen
Age 29
Name: miki
Age 30
Let us try to understand more about keyword argument with the help of following function
definition −
150
division(10,5)
division(5,10)
Since the values are assigned as per the position, the output is as follows −
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)
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.
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.
It will print −
Hello-World
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.
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.
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
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
phy = 60
maths = 70
result = percent(phy,maths)
print ("percentage:", result)
phy = 40
maths = 46
result = percent(phy,maths, 100)
print ("percentage:", result)
percentage: 65.0
154
percentage: 86.0
def sum_all(*args):
result = 0
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):
print(f"{key}: {value}")
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.
print("Positional arguments:")
156
for arg in args:
print(arg)
print("Keyword arguments:")
print(f"{key}: {value}")
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.
157
print(f"X: {x}, Y: {y}, Z: {z}, W: {w}")
coordinates = [1, 2, 3, 4]
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.
print(a, b, c, d)
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
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.
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.
Output
159
Following is an output of the above code -
Alternate Solution
def triangle(m,n):
return 1/2 * m * n
print(triangle(4,6))
Output
12.0
Note - It's not necessary for the expression to always return a value. The lambda function as
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 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.
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 -
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
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
161
the cube of each number iteratively evaluated against in the list. The map function's outcome is
then printed.
Output
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
Note - The reduce() function is imported from the module named functools. This module
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.
Output
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
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's standard library includes a built-in function globals(). It returns a dictionary of symbols
>>> 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 −
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())
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.
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.
myfunction()
print (marks) # prints global value
70
50
If you try to manipulate value of a global variable from inside a function, Python
167
raises UnboundLocalError.
myfunction()
print (marks) # prints global value
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.
myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values
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.
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
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 [].
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.
# Creation of List
# Creating a List
List = []
print(List)
print(List)
# using index
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)
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.
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
171
print(List)
print(List)
Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
172
List = ["Geeks", "For", "Geeks"]
print(List[0])
print(List[2])
Output
Accessing a element from the list
Geeks
Geeks
Example 2: Accessing elements from a multi-dimensional list
# index number
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.
# negative indexing
print(List[-1])
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))
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:
175
# input the list as string
lst = string.split()
Output:
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
Example 2:
elements:").strip().split()))[:n]
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
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.
# Creating a List
List = []
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print(List)
177
# Adding elements to the List
# using Iterator
List.append(i)
print(List)
List.append((5, 6))
print(List)
List.append(List2)
print(List)
Output
Initial blank List:
[]
178
[1, 2, 4]
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).
# Creating a List
List = [1,2,3,4]
print(List)
# Addition of Element at
179
# specific Position
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)
Output
Initial List:
[1, 2, 3, 4]
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.
# Creating a List
180
List = [1, 2, 3, 4]
print(List)
print(List)
Output
Initial List:
[1, 2, 3, 4]
# Reversing a list
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
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:
182
# Creating a List
List = [1, 2, 3, 4, 5, 6,
print(List)
List.remove(5)
List.remove(6)
print(List)
Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# Creating a List
List = [1, 2, 3, 4, 5, 6,
183
7, 8, 9, 10, 11, 12]
List.remove(i)
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)
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]
List.pop()
184
print("\nList after popping an element: ")
print(List)
# Removing element at a
List.pop(2)
print(List)
Output
List after popping an element:
[1, 2, 3, 4]
185
[Index:]
To print the whole list in reverse order, use
[::-1]
Note – To print elements of List from rear-end, use Negative Indexes.
# Creating a List
186
print("Initial List: ")
print(List)
Sliced_List = List[3:8]
print(Sliced_List)
Sliced_List = List[5:]
print(Sliced_List)
Sliced_List = List[:]
print(Sliced_List)
Output
187
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
# Creating a List
print(List)
Sliced_List = List[:-6]
188
print(Sliced_List)
Sliced_List = List[-6:-1]
print(Sliced_List)
Sliced_List = List[::-1]
print(Sliced_List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
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:
# comprehension in Python
print(odd_square)
Output
[1, 9, 25, 49, 81]
For better understanding, the above code is similar to as follows:
odd_square = []
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
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.
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
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
any() return true if any element of the list is true. if the list is empty, return false
192
Function Description
apply a particular function passed in its argument to all of the list elements
accumulate()
returns a list containing the intermediate results
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.
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.
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)
print(mytuple[1])
print(mytuple[4])
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.
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)
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
196
Concatenation
Nesting
Repetition
Slicing
Deleting
Finding the length
Multiple Data Types with tuples
Conversion of lists to tuples
Tuples in a Loop
tuple1 = (0, 1, 2, 3)
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
tuple1 = (0, 1, 2, 3)
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
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
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
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
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_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
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
tup = ('geek',)
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.
201
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
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(Dict)
print(Dict)
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'}
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.
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
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(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
Dict['Value_set'] = 2, 3, 4
print(Dict)
Dict[2] = 'Welcome'
print(Dict)
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'}}}
print(Dict['name'])
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
print(Dict.get(3))
Output:
Accessing a element using get:
Geeks
207
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
print("Dictionary =")
print(Dict)
del(Dict[1])
print(Dict)
Output
208
Dictionary methods
Method Description
209
Method Description
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
type(var)
Output:
set
Time Complexity: O(1)
Auxiliary Space: O(1)
211
Type Casting with Python Set method
Python3
print(myset)
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)
Python sets cannot have a duplicate value and once it is created we cannot change its value.
Python3
212
# a set cannot have duplicate values
print(myset)
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
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
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
214
print("Normal Set")
print(normal_set)
# A frozen set
print("\nFrozen Set")
print(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:
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
# in a set
# Creating a Set
print(people)
# in the set
people.add("Daxit")
217
for i in range(1, 6):
people.add(i)
print(people)
Output:
People: {'Idrish', 'Archi', 'Jay'}
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
218
vampires = {"Karan", "Arjun"}
# function
population = people.union(vampires)
print(population)
# operator
population = people|dracula
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)
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(set3)
# Intersection using
# "&" operator
print(set3)
Output:
Intersection using intersection() function
{3, 4}
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)
set3 = set1.difference(set2)
222
print(set3)
print(set3)
Output:
Difference of two sets using difference() function
{0, 1, 2}
Python3
# Python program to
# demonstrate clearing
223
# of set
set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)
set1.clear()
print(set1)
Output:
Initial set
{1, 2, 3, 4, 5, 6}
224
Operation Average case Worst Case notes
x in s O(1) O(n)
replace “min”
O(min(len(s),
Intersection s&t O(len(s) * len(t)) with “max” if t is
len(t))
not a set
Operators Notes
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1 is subset of s2
225
Operators Notes
s1 >= s2 s1 is superset of s2
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 −
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
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
if 30 in myList1:
print('30 is present')
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 = []
229
if var % 2 == 0:
output_list.append(var)
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)
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 = []
output_list.append(var ** 2)
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)
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 = {}
if var % 2 != 0:
output_dict[var] = var**3
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}
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
output_dict = {}
output_dict[key] = value
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
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()
if var % 2 == 0:
output_set.add(var)
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]
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:
Output values using generator comprehensions: 2 4 4 6
236