SlideShare a Scribd company logo
1 of 162
Revolutionising B.Tech.
Module-2
Data Structures, Functions and Recursion
Aim
To equip students in the fundamentals and understanding of
To equip students with a strong foundation in
Python programming, focus on comprehensive
understanding and practical application of
fundamental concepts and implementation of
python programs
 Explain the objective of learning Python
programming, emphasizing proficiency in string
manipulation and list operations. Illustrate
the application through programming tasks.
Outline:
• Data Structures:
• Lists,
• Dictionaries, Mutability and References,
• Tuples,
• Sets and Collections,
• Function:
• User-defined function basics,
• Returning values from functions,
• Function stubs, Functions: Common errors,
• Function arguments: Variable number of arguments,
• Anonymous functions
• Recursive functions
• Map, filter and reduce, list comprehensions, cartesian product, itertools, eval, exec, enumerate,
zip, copy,,
• Recursive algorithm: Search, adding output statements for debugging.
Python List
List:
• A list is a compound data type, which is used to group values together
• A list contains items separated by commas and enclosed within square brackets ([]).
• Lists are similar to arrays in C.
• One difference between them is that the items belonging to a list can be of different data
type.
• The values stored in a list can be accessed using the [ ] operator
• Index starts at 0.
Creating List:
Accessing Elements of List:
Exercise
Filling list with variables:
Exercise
@instructions
• Create a list, areas, that contains the area of the
hallway (hall), kitchen (kit), living room (liv),
bedroom (bed) and bathroom (bath), in this
order. Use the predefined variables.
• Print areas with the print() function.
@hint
• You can use the variables that have already
been created to build the list: areas = [hall, kit,
...].
• Put print(areas) in your script to print out the list
when submitting.
@sample_code
# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
# Create list areas
# Print areas
Exercise
@sample_code
# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
# Create list areas
# Print areas
@Solution
# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
# Create list areas
areas = [hall, kit, liv, bed, bath]
# Print areas
print(areas)
[11.25, 18.0, 20.0, 10.75, 9.5]
List Functions
List Functions
List Functions
List Concatenation
Repeating sequence with * operator:
Forming new lists with a repeating sequence using the multiplication
operator:
Create a list of 5 elements with initial value as 0
Built-in List Methods
Insertion
Append(ele) Add element at end of List
Insert(index , ele) Add element at given index
Extend( seq ) Appends all the elements of seq to list
Deletion Pop(index) Delete element based on Index
Remove(key) Delete element based on key
Count(key) Returns the number of occurrences of key
Index(key) Returns the index of key element
Sort Sorts elements of List
Reverse Reverses elements of list
Append: Add elements to list
• We can add elements to list.
• To add one element, use append method.
• This adds an item to the end of an existing list.
mylist = [ ]
mylist.append(5)
mylist.append(8)
mylist.append(12)
#prints [5,8,12]
print(mylist)
Append: Add elements to list
Insert Method:
• insert(index, element)
Adding Elements to list: extend
• We can add a series of elements using extend method or + operator.
Adding Elements to List: Extend
• a = [1,2,3]
• b = [4,5,6]
• Understand the difference between
• a.append(b) and
• a.extend(b)
Deleting Elements from List:
• To delete last element
Delete Element from List:
• To delete element at specific Index
Removing a specific element
• Remove method takes the key element to delete and removes it if present.
Index Method:
• index() method finds the given element in a list and returns its position.
• If the same element is present more than once, index() method returns its
smallest/first position.
• If not found, it raises
• a ValueError exception indicating the element is not in the list.
Index Method:
• The index method finds the first occurrence of a list item and returns its index.
• If the item isn't in the list, it raises a ValueError.
• letters = ['p', 'q', 'r', 's', 'p', 'u']
• print(letters.index('r'))
• print(letters.index('p'))
• print(letters.index('z'))
2
0
ValueError: 'z' is not in list
Sorting List:
• The sort method can be used to sort the elements of the list.
Sorting in Descending Order:
Sorting Based on Length:
Sorting Based on Length:
List Slicing:
mylist = [5 , 8 ,
12 , 20 , 25,
50]
mylist[startIndex : endIndex]
Comparing two list
• == operator is used to check if two list have same elements.
• is operator is used to check if two references refer to same list.
Nested List:
Nested List
Calculating BMI
• BMI = weight/height2
• height= [ 1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
• weight= [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
• bmi = weight / (height ** 2)
Calculating BMI:
• BMI = weight/height2
• height =[ 1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
• weight= [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
• bmi = []
• n = len(height)
• for i in range(0,n):
• bmi.append(weight[i] / (height[i] ** 2))
• print (bmi)
Mutability
• Mutable is when something is changeable.
• It’s the ability of objects to change their values.
• Objects of built-in type that are mutable are:
Lists
Sets
Dictionaries
User-Defined Classes (It purely depends upon the user to define the characteristics)
Mutability Examples:
• Real time example for mutability is grocery list.
• The below figure shows what happens in memory when you bind variables to mutable objects.
• When you modify the object, you keep the same variable binding and the object at the same
memory location’s directly modified.
References
• Python program accesses data values through references
• A reference is a name that refers to the specific location in memory of a value (object).
• References take the form of variables, attributes, and items.
• A reference variable is a variable that points to an object of a given class, letting you access the
value of an object.
• . Attributes are variables of a class that are shared between all of its instances.
All Function:
• The all() function returns True if all elements of the supplied iterable are true or if there are no
elements.
• So, if all elements in a list, tuple, or set match Python's definition of being true, then all() returns
True.
Any Function:
• The any() function is the converse of the all() function. any() returns True if any element of the
iterable evaluates true.
• If the iterable is empty, the function returns False.
Zip Function
• The zip() function take iterables, makes iterator that aggregates elements based on the iterables
passed, and returns an iterator of tuples.
Common errors:
• Wrong Function Definition and Function Call Order
Example:
Calling the function even before you define your function. The function definition runs first and
creates the function in python programming before you can call it. If you call the function earlier than
python will throw an error.
Common errors:
• Parameter Mismatch Error
Example:
when you call the function with either wrong parameter type or less number of parameters, python
will throw an error in each case.
Common errors:
• Scope Error
Example:
This is possible in the case of a conditional block such as if, if-then-else, etc. This is called a scope
error..
Python Tuples
Python Tuples
• Tuples are very similar to lists, except that they are immutable (they cannot be changed).
They are created using parentheses, rather than square brackets.
Python Tuples
• We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar)
datatypes.
• Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
• Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not
possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.
3
Creating a Tuple
• A tuple is created by placing all the items (elements) inside a parentheses (), separated by
comma.
• The parentheses are optional but is a good practice to write it.
• A tuple can have any number of items and they may be of different types (integer, float, list, string
etc.).
3
Creating a Tuple
• Creating a tuple with one element is a bit tricky.
• Having one element within parentheses is not enough.
• We will need a trailing comma to indicate that it is in fact a tuple.
Accessing Elements in a Tuple
• You can access the values in the tuple with their index, just as you did with lists:
• Nested tuple are accessed using nested indexing
• Negative indexing can be applied to tuples similar to lists.
• We can access a range of items in a tuple by using the slicing operator
• Trying to reassign a value in a tuple causes a TypeError.
Changing a Tuple
• Unlike lists, tuples are immutable.
• This means that elements of a tuple cannot be changed once it has been assigned. But, if the
element is itself a mutable datatype like list, its nested items can be changed.
Changing a Tuple
Similar to List,
• We can use + operator to combine two tuples. This is also called concatenation.
• We can also repeat the elements in a tuple for a given number of times using the * operator.
• Both + and * operations result into a new tuple.
Deleting a Tuple
• We cannot change the elements in a tuple. That also means we cannot delete or remove items
from a tuple.
• But deleting a tuple entirely is possible using the keyword del.
Python Tuple Methods
• Methods that add items or remove items are not available with tuple.
• Only the following two methods are available.
Method Description
count(x) Return the number of items that is equal to
x
index(x) Return index of first item that is equal to x
Tuple Membership Test
• We can test if an item exists in a tuple or not, using the keyword in.
Iterating Through a Tuple
• Using a for loop we can iterate though each item in a tuple.
Function Description
all() Return True if all elements of the tuple are true (or if the
tuple is empty).
any() Return True if any element of the tuple is true. If the tuple is
empty, return False.
enumerate()
Return an enumerate object. It contains the index and value
of all the items of
tuple as pairs.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
sorted()
Take elements in the tuple and return a new sorted list
(does not sort the tuple itself).
sum() Retrun the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.
Built-in Functions with Tuple
Python Sets
Sets Definition:
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Tuple, and Dictionary.
• Syntax of set:
where <iter> : iterable can be anything like list, tuple,etc. List and tuple are the other built-in data
structures in python just like settings.
Example:
The other way to create a set in python is to define the elements in a set of curly braces: The
syntax for the same is shown as follows:
Exercise
• Given a list of elements, remove the duplicate elements.
Exercise
• Read a string and find the number of unique characters in it.
Exercise
Sets
• Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference.
• We can do this with operators or methods.
Method Operator
union |
intersection &
difference -
symmetric_difference ^
Example
Operators
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
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
Example
Example
Example
Set Mutation Operations
• We have seen the applications of union, intersection, difference and symmetric difference
operations, but these operations do not make any changes or mutations to the set.
• We can use the following operations to create mutations to a set:
Method Operator
update |= Update the set by adding elements
from an iterable/another set.
intersection_update &= Update the set by keeping only
the elements found in it and an
iterable/another set.
Difference_update -= Update the set by removing
elements found in an
iterable/another set.
symmetric_difference_update ^= Update the set by only keeping
the elements found in either set,
but not in both.
Set Mutation Operations
• Isdisjoint– This method will return True if two set have a null intersection
• Issubset – This method reports whether another set contains this set
• Issuperset – This method will report whether this set contains another set
Set Mutation Operations
Python Dictionary
Python Dictionary:
• In Python, a dictionary is a set of keys and values that can be used to store data values like a
map, in contrast to other data types that can only contain a single value per element.
More on Dictionary:
• An unordered collection of elements is a Python dictionary.
• In contrast to other compound data types, dictionaries include a key:value pair.
• When the key is known, dictionaries are designed to retrieve values quickly.
Creating a Dictionary:
• By putting a series of components within curly brackets and separating them with a comma, one
can create a dictionary in Python.
• Dictionary has two equivalent pair elements, one of which is the Key and the other is its Key:value.
• A dictionary's values can be of any data type and can be replicated, but its keys must be
immutable and cannot be repeated.
• Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
Example:
• marks = {“Maths” : 34, “Science” : 22 ,”English” :56}
• print(marks)
• xyz = {“Name” : ‘Tina’, 1:[2,4,1,7]}
• print(xyz)
• Dictionary = { }
• print(“Empty Dictionary”,Dictionary)
Inbuilt dict() function:
• Dict = dict({1: ‘Apple', 2: ‘Andriod', 3: ‘Tablet'})
• print("nDictionary with the use of dict(): ")
• print(Dict)
• # Creating a Dictionary
• # with each item as a Pair
• Dict = dict([(1, ‘Lamborgini'), (2, ‘BMW')])
• print("nDictionary with each item as a pair: ")
• print(Dict)
Nested Dictionary:
• # Creating a Nested Dictionary
• DT = {1: 'Jain', 2: 'University',
• 3: {'A': 'Welcome', 'B': 'To', 'C': 'SET'}}
• print(DT)
Adding element(s) to a Dictionary:
• Multiple methods can be used to add items.
• By defining the value and the key together, for example, Dict[Key] = "Value," one value can be
added to a dictionary at a time.
• Using the built-in update() method, one can modify an existing value in a Dictionary.
• An existing Dictionary may also be expanded with nested key values.
• Note: When adding a value, the value is updated if the key-value combination already exists. If
not, a new key and value are added to the dictionary.
Example:
• # Adding elements one at a time
• Dict[0] = 'Jain'
• Dict[2] = 'University'
• Dict[3] = 10
• print("nDictionary after adding 3 elements: ")
• print(Dict)
Example:
• # Adding set of values to a single Key
• Dict['Value_set'] = 24, 3, 43
• print("nDictionary after adding 3 elements: ")
• print(Dict)
Example:
• # Adding Nested Key value to Dictionary
• Dict[5] = {'Nested': {'1': 'Deemed', '2': 'To be University'}}
• print("nAdding a Nested Key: ")
• print(Dict)
Solution:
Accessing element of a Dictionary:
Solution:
Accessing an element of a nested dictionary
Dictionary Methods:
clear() Remove all the elements from the
dictionary
copy() Returns a copy of the dictionary
get() Returns the value of specified key
items() Returns a list containing a tuple for
each key value pair
keys() Returns a list containing dictionary’s
keys
pop() Remove the element with specified
key
popitem() Removes the last inserted key-value
pair
update() Updates dictionary with specified key-
value pairs
values() Returns a list of all the values of
dictionary
Dictionary Methods:
Examples for all Dictionary Methods
Examples for all Dictionary Methods
Python Functions
96
Function Definition:
• It is not advised to write a collection of statements separately if they are needed repeatedly.
• These statements must be defined as one unit, which we can then call as many times as
necessary to meet our requirements without having to rewrite anything.
• Function alone defines this apparatus.
Function Definition:
• The main advantage of functions is code Reusability.
• Note: In other languages, functions are known as methods, procedures, subroutines, etc.
• Python supports 2 types of functions
• Built In Functions
• User DefinedFunctions
Built In Functions:
• Built-in or predefined functions refer to the functions that are automatically included with Python
software.
• id()
• type()
• input()
• eval()
User defined functions:
• User defined functions are those that are explicitly developed by programmers in accordance with
business requirements.
• Syntax:
• def function_name(parameters):
• statements
• return value
Keywords
Function Call
• Once we have defined a function, we can call it from another function, program or even the Python
prompt.
• To call a function we simply type the function name with appropriate parameters.
Calling the Function
my_function()
Example: WA Function to print “BE YOU,DO YOU ,FOR YOU
Parameters:
• The function's inputs are the parameters.
• If a function has parameters, we must provide values at the time of calling; otherwise, we will
receive an error.
Write a function to get square of user input number:
Return Statement:
• Function can take input values as parameters and execute the logic, and return the output to the
caller with return statement.
Return Statement:
• If we are not mentioning return statement, then default return value is None.
Exercise: WA function to find whether the given number is even or
odd:
Function returning multiple value
Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the variable is recognized.
• Parameters and variables defined inside a function is not visible from outside. Hence, they have a
local scope.
• Lifetime of a variable is the period throughout which the variable exits in the memory.The lifetime
of variables inside a function is as long as the function executes.
• They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
Scope and Lifetime of variables
Scope and Lifetime of variables
Scope and Lifetime of variables
Types of Arguments
• There are 4 types are actual arguments are allowed In Python.
• Positional Arguments
• Keyword Arguments
• Default Arguments
• Variable length Arguments
Positional Arguments:
• These are the arguments passed to function in correct positional order.
• The number of arguments and position of arguments must be matched. If we change the order
then result may be changed and if number of arguments differ, then we will get error.
Positional Arguments:
Keyword Arguments:
• We can pass argument values by keyword i.e, by parameter name.
• Here the order of arguments is not important but number of arguments must be matched.
• Note; We can use both positional and keyword arguments at the same time. But first we have to
take positional arguments and then keyword arguments, else we will get syntaxerror.
Keyword Arguments
Keyword Arguments
Keyword Arguments
Default Arguments
• Function arguments can have default values in Python.
• We can provide a default value to an argument by using the assignment operator (=).
Default Arguments:
• In this function, the parameter amount does not have a default value and is required (mandatory)
during a call.
• On the other hand, the parameter discountPercentage has a default value of 0. So, it is optional
during a call.
• If a value is provided, it will overwrite the default value.
• Any number of arguments in a function can have a default value.
Default Arguments
• Once we have a default argument, all the arguments to its right must also have default values.
• SyntaxError: non-default argument follows default argument
Variable Length Arguments:
• Variable length arguments are those that we can occasionally supply to our function in a variable
number.
• The following symbol can be used to declare an argument of variable length: def func(*n):
• Any number of parameters, even zero, may be sent to this function when calling it, and all of the
values are internally represented as tuples.
Variable number of arguments
Functions as Objects
• Although functions are created differently from normal variables, functions are just like any other
kind of value.
• They can be assigned and reassigned to variables, and later referenced by those names.
Functions as Objects
Recursive Functions:
• A function that calls itself is known as Recursive Function.
• Advantages of recursive functions are:
• We can reduce length of the code and improves readability.
• We can solve complex problems very easily.
Recursive Functions:
Recursive Algorithms:
• A recursive algorithm is an algorithm which calls itself with a smaller problem.
• If a problem can be solved utilizing solutions to smaller versions of the same problem and the
smaller versions reduce to easily solvable cases, then one can use a recursive algorithm to solve
that problem.
• They are of two types: indirect and direct recursion
• Example :Code for determining if a given list contains a given string
Search using recursive Algorithms:
Recursive explorations of all possibility :
• This is supposed to return a list back to the use with all the possible permutations.
• Example :Code to return all possible permutation of string.
Anonymous Function:
• When a function is declared, it may not have a name.
• These types of nameless functions are known as anonymous functions or lambda functions.
• The anonymous function's primary use is only for one-time, instantaneous use.
Lambda Function:
• Lambda keyword lambda n:n•n allows us to define.
• Lambda syntax
• Expression: lambda argument list: function
• Note: By using lambda functions, we may create extremely brief code, improving the readability of
the program.
Lambda Function:
• Write a Program to create a Lambda Function to find Square of given Number?
Sum of numbers using lambda:
Find largest of numbers using lambda:
Note
• We are not required to write an explicit return statement because Lambda Functions return
expression values internally.
• It should be noted that functions can occasionally be passed as arguments to other functions.
• The best option in these situations is lambda functions.
• Due to the fact that filter(), map(), and reduce() expect a function as an argument, lambda
functions are frequently used with these functions.
filter() Function:
• filter() function is used to filter values from the given sequence based on some condition.
• filter(function(sequence))
• Where Function Argument is responsible to perform conditional check Sequence can be List OR
Tuple OR String.
filter() Function:
Using lambda and filter():
map() function:
• Python’s map() function takes in a list and another function.
• The function argument is called with all elements in the list and returns a new list containing
elements returned from each element in the original list.
• Syntax: map(function,sequence)
map() function:
With lambda and map():
reduce() function:
• reduce() function reduces the sequence of elements Into a single element by applying the
specified function.
• Syntax: reduce(function, sequence)
• reduce() function is present in functools module and hence we should write import statement.
eval() function:
• This will allows you to evaluate arbitrary Python expressions from a string-based or compiled-
code-based.
• This function can be handy when you're trying to dynamically evaluate Python expressions from
any input that comes as a string or a compiled code object.
• Syntax of eval()
zip() function:
• zip() function returns a zip object.
• This is an iterator of tuples where the first item in each passed iterator is paired together, and then
the second item in each passed iterator are paired together etc.
• Syntax of zip()
Example:
Cartesian Product:
• Suppose we have 2 list of data list1 and list2.
• To find the cartesian product of (a,b) and (c,d) = {(a,c),(a,d),(b,c),(b,d)}
• To find this , we will use the itertools library and product function which is present in this library.
exec() function:
• The exec() function is used to execute Python program dynamically.
• These program can either be strings or object code.
• If it's a string, it's translated into a series of Python statements that are then performed, barring any
syntax errors; if it's object code, it's just executed.
• Using return statements outside of function declarations, not even in the context of code provided
to the exec() method, requires caution.
• It returns None since it has no value to return.
exec() function:
copy() function:
• The copy() method returns a copy of the list.
enumerate():
• Returns an enumerate object which contains the value and index of all list elements as tuple.
• Returns an enumerate object which contains the value and index of all set elements as a pair.
• Returns an enumerate object containing the value and index of all tuple elements as pairs.
enumerate():
List Comprehensions:
• It is very easy and compact way of creating list objects from any lterableobjects (like list,Tuple,
Dictionary, Range.etc) based on some condition.
• Syntax:
• list=[expression for elements in list if conditions]
List Comprehensions:
LIST Vs TUPLE Vs SETS:
List Tuple Set
Lists is Mutable Tuple is Immutable Set is Mutable
It is Ordered collection of
items
It is Ordered collection of
items
It is Unordered collection of
items
Items in list can be replaced
or changed
Items in tuple cannot be
changed or replaced
Items in set cannot be
changed or replaced
Mutable:
• When anything can be altered or changed, it is said to be mutable. The term "mutable" in Python
refers to an object's capacity to modify its values. These are frequently the things that hold a data
collection.
• Immutable: Immutable refers to a state in which no change can occur over time. An object is
referred to as immutable in Python if its value cannot change over time. The worth of these things
is fixed once they are made.
Adding output comment for debugging:
• The logging module has everything.
• Its recommend using logging.basicConfig to toggle the logging level to stderr and the simple log
methods, debug, info, warning, error and critical.
• Code sample below is used for logging:
•
Terminal Questions
1. Write a Python function that takes a list of integers as input and returns a new list containing
only the even numbers from the original list.
2. Given a dictionary of student names and their corresponding grades, write a function that takes
the dictionary as input and returns the names of students who have scored above a certain
grade threshold (e.g., 80).
Reference
1. Lutz, Mark (2013). Learning Python (5th ed.). O'Reilly Media.
2. https://www.w3schools.com/python/python_intro.asp
3. https://www.geeksforgeeks.org/python-programming-language/
4. https://docs.python.org/3/tutorial/index.html
5. https://www.javatpoint.com/python-tutorial
6. https://www.coursera.org/learn/python-programming-intro
7. https://www.javatpoint.com/python-tutorial
Thank You!

More Related Content

Similar to MODULE-2.pptx

Built-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfBuilt-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfalivaisi1
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 
2. Values and Data types in Python.pptx
2. Values and Data types in Python.pptx2. Values and Data types in Python.pptx
2. Values and Data types in Python.pptxdeivanayagamramachan
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonchanna basava
 
Acm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAcm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAhmad Bashar Eter
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsBlue Elephant Consulting
 
python presentation.pptx
python presentation.pptxpython presentation.pptx
python presentation.pptxNightTune44
 
Data Structure & Algorithms - Operations
Data Structure & Algorithms - OperationsData Structure & Algorithms - Operations
Data Structure & Algorithms - Operationsbabuk110
 

Similar to MODULE-2.pptx (20)

set.pptx
set.pptxset.pptx
set.pptx
 
Python_basics.pptx
Python_basics.pptxPython_basics.pptx
Python_basics.pptx
 
Built-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfBuilt-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdf
 
lecture 02.2.ppt
lecture 02.2.pptlecture 02.2.ppt
lecture 02.2.ppt
 
Intro to Lists
Intro to ListsIntro to Lists
Intro to Lists
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
2. Values and Data types in Python.pptx
2. Values and Data types in Python.pptx2. Values and Data types in Python.pptx
2. Values and Data types in Python.pptx
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
Acm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAcm aleppo cpc training seventh session
Acm aleppo cpc training seventh session
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List Algorithms
 
Chapter - 2.pptx
Chapter - 2.pptxChapter - 2.pptx
Chapter - 2.pptx
 
Tuples.pptx
Tuples.pptxTuples.pptx
Tuples.pptx
 
unit1 python.pptx
unit1 python.pptxunit1 python.pptx
unit1 python.pptx
 
Elements of functional programming
Elements of functional programmingElements of functional programming
Elements of functional programming
 
ds bridge.pptx
ds bridge.pptxds bridge.pptx
ds bridge.pptx
 
CH05.ppt
CH05.pptCH05.ppt
CH05.ppt
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
python presentation.pptx
python presentation.pptxpython presentation.pptx
python presentation.pptx
 
Data Structure & Algorithms - Operations
Data Structure & Algorithms - OperationsData Structure & Algorithms - Operations
Data Structure & Algorithms - Operations
 

Recently uploaded

VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackVIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackSuhani Kapoor
 
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...Suhani Kapoor
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士obuhobo
 
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home MadeDubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Madekojalkojal131
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjLewisJB
 
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call GirlsDelhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girlsshivangimorya083
 
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...Call Girls in Nagpur High Profile
 
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳anilsa9823
 
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service CuttackVIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service CuttackSuhani Kapoor
 
(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...
(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...
(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...gurkirankumar98700
 
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...Suhani Kapoor
 
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证obuhobo
 
Zeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effectZeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effectPriyanshuRawat56
 
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...Suhani Kapoor
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...shivangimorya083
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...shivangimorya083
 
CALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual serviceanilsa9823
 
PM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring ChapterPM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring ChapterHector Del Castillo, CPM, CPMM
 
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service BhiwandiVIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service BhiwandiSuhani Kapoor
 

Recently uploaded (20)

VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackVIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
 
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
 
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home MadeDubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbj
 
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call GirlsDelhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
 
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...
 
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
 
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service CuttackVIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
 
(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...
(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...
(Call Girls) in Lucknow Real photos of Female Escorts 👩🏼‍❤️‍💋‍👩🏻 8923113531 ➝...
 
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
 
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
 
Zeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effectZeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effect
 
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
 
CALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gosainganj Lucknow best sexual service
 
PM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring ChapterPM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring Chapter
 
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service BhiwandiVIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
VIP Call Girl Bhiwandi Aashi 8250192130 Independent Escort Service Bhiwandi
 

MODULE-2.pptx

  • 3. Aim To equip students in the fundamentals and understanding of To equip students with a strong foundation in Python programming, focus on comprehensive understanding and practical application of fundamental concepts and implementation of python programs
  • 4.  Explain the objective of learning Python programming, emphasizing proficiency in string manipulation and list operations. Illustrate the application through programming tasks.
  • 5. Outline: • Data Structures: • Lists, • Dictionaries, Mutability and References, • Tuples, • Sets and Collections, • Function: • User-defined function basics, • Returning values from functions, • Function stubs, Functions: Common errors, • Function arguments: Variable number of arguments, • Anonymous functions • Recursive functions • Map, filter and reduce, list comprehensions, cartesian product, itertools, eval, exec, enumerate, zip, copy,, • Recursive algorithm: Search, adding output statements for debugging.
  • 7. List: • A list is a compound data type, which is used to group values together • A list contains items separated by commas and enclosed within square brackets ([]). • Lists are similar to arrays in C. • One difference between them is that the items belonging to a list can be of different data type. • The values stored in a list can be accessed using the [ ] operator • Index starts at 0.
  • 11. Filling list with variables:
  • 12. Exercise @instructions • Create a list, areas, that contains the area of the hallway (hall), kitchen (kit), living room (liv), bedroom (bed) and bathroom (bath), in this order. Use the predefined variables. • Print areas with the print() function. @hint • You can use the variables that have already been created to build the list: areas = [hall, kit, ...]. • Put print(areas) in your script to print out the list when submitting. @sample_code # area variables (in square meters) hall = 11.25 kit = 18.0 liv = 20.0 bed = 10.75 bath = 9.50 # Create list areas # Print areas
  • 13. Exercise @sample_code # area variables (in square meters) hall = 11.25 kit = 18.0 liv = 20.0 bed = 10.75 bath = 9.50 # Create list areas # Print areas @Solution # area variables (in square meters) hall = 11.25 kit = 18.0 liv = 20.0 bed = 10.75 bath = 9.50 # Create list areas areas = [hall, kit, liv, bed, bath] # Print areas print(areas) [11.25, 18.0, 20.0, 10.75, 9.5]
  • 18. Repeating sequence with * operator: Forming new lists with a repeating sequence using the multiplication operator: Create a list of 5 elements with initial value as 0
  • 19. Built-in List Methods Insertion Append(ele) Add element at end of List Insert(index , ele) Add element at given index Extend( seq ) Appends all the elements of seq to list Deletion Pop(index) Delete element based on Index Remove(key) Delete element based on key Count(key) Returns the number of occurrences of key Index(key) Returns the index of key element Sort Sorts elements of List Reverse Reverses elements of list
  • 20. Append: Add elements to list • We can add elements to list. • To add one element, use append method. • This adds an item to the end of an existing list. mylist = [ ] mylist.append(5) mylist.append(8) mylist.append(12) #prints [5,8,12] print(mylist)
  • 23. Adding Elements to list: extend • We can add a series of elements using extend method or + operator.
  • 24. Adding Elements to List: Extend • a = [1,2,3] • b = [4,5,6] • Understand the difference between • a.append(b) and • a.extend(b)
  • 25. Deleting Elements from List: • To delete last element
  • 26. Delete Element from List: • To delete element at specific Index
  • 27. Removing a specific element • Remove method takes the key element to delete and removes it if present.
  • 28. Index Method: • index() method finds the given element in a list and returns its position. • If the same element is present more than once, index() method returns its smallest/first position. • If not found, it raises • a ValueError exception indicating the element is not in the list.
  • 29. Index Method: • The index method finds the first occurrence of a list item and returns its index. • If the item isn't in the list, it raises a ValueError. • letters = ['p', 'q', 'r', 's', 'p', 'u'] • print(letters.index('r')) • print(letters.index('p')) • print(letters.index('z')) 2 0 ValueError: 'z' is not in list
  • 30. Sorting List: • The sort method can be used to sort the elements of the list.
  • 32. Sorting Based on Length:
  • 33. Sorting Based on Length:
  • 34. List Slicing: mylist = [5 , 8 , 12 , 20 , 25, 50] mylist[startIndex : endIndex]
  • 35. Comparing two list • == operator is used to check if two list have same elements. • is operator is used to check if two references refer to same list.
  • 38. Calculating BMI • BMI = weight/height2 • height= [ 1.87, 1.87, 1.82, 1.91, 1.90, 1.85] • weight= [81.65, 97.52, 95.25, 92.98, 86.18, 88.45] • bmi = weight / (height ** 2)
  • 39. Calculating BMI: • BMI = weight/height2 • height =[ 1.87, 1.87, 1.82, 1.91, 1.90, 1.85] • weight= [81.65, 97.52, 95.25, 92.98, 86.18, 88.45] • bmi = [] • n = len(height) • for i in range(0,n): • bmi.append(weight[i] / (height[i] ** 2)) • print (bmi)
  • 40. Mutability • Mutable is when something is changeable. • It’s the ability of objects to change their values. • Objects of built-in type that are mutable are: Lists Sets Dictionaries User-Defined Classes (It purely depends upon the user to define the characteristics)
  • 41. Mutability Examples: • Real time example for mutability is grocery list. • The below figure shows what happens in memory when you bind variables to mutable objects. • When you modify the object, you keep the same variable binding and the object at the same memory location’s directly modified.
  • 42. References • Python program accesses data values through references • A reference is a name that refers to the specific location in memory of a value (object). • References take the form of variables, attributes, and items. • A reference variable is a variable that points to an object of a given class, letting you access the value of an object. • . Attributes are variables of a class that are shared between all of its instances.
  • 43. All Function: • The all() function returns True if all elements of the supplied iterable are true or if there are no elements. • So, if all elements in a list, tuple, or set match Python's definition of being true, then all() returns True.
  • 44. Any Function: • The any() function is the converse of the all() function. any() returns True if any element of the iterable evaluates true. • If the iterable is empty, the function returns False.
  • 45. Zip Function • The zip() function take iterables, makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.
  • 46. Common errors: • Wrong Function Definition and Function Call Order Example: Calling the function even before you define your function. The function definition runs first and creates the function in python programming before you can call it. If you call the function earlier than python will throw an error.
  • 47. Common errors: • Parameter Mismatch Error Example: when you call the function with either wrong parameter type or less number of parameters, python will throw an error in each case.
  • 48. Common errors: • Scope Error Example: This is possible in the case of a conditional block such as if, if-then-else, etc. This is called a scope error..
  • 50. Python Tuples • Tuples are very similar to lists, except that they are immutable (they cannot be changed). They are created using parentheses, rather than square brackets.
  • 51. Python Tuples • We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes. • Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost. • Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible. • If you have data that doesn't change, implementing it as tuple will guarantee that it remains write- protected. 3
  • 52. Creating a Tuple • A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. • The parentheses are optional but is a good practice to write it. • A tuple can have any number of items and they may be of different types (integer, float, list, string etc.). 3
  • 53. Creating a Tuple • Creating a tuple with one element is a bit tricky. • Having one element within parentheses is not enough. • We will need a trailing comma to indicate that it is in fact a tuple.
  • 54. Accessing Elements in a Tuple • You can access the values in the tuple with their index, just as you did with lists: • Nested tuple are accessed using nested indexing • Negative indexing can be applied to tuples similar to lists. • We can access a range of items in a tuple by using the slicing operator • Trying to reassign a value in a tuple causes a TypeError.
  • 55. Changing a Tuple • Unlike lists, tuples are immutable. • This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed.
  • 56. Changing a Tuple Similar to List, • We can use + operator to combine two tuples. This is also called concatenation. • We can also repeat the elements in a tuple for a given number of times using the * operator. • Both + and * operations result into a new tuple.
  • 57. Deleting a Tuple • We cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple. • But deleting a tuple entirely is possible using the keyword del.
  • 58. Python Tuple Methods • Methods that add items or remove items are not available with tuple. • Only the following two methods are available. Method Description count(x) Return the number of items that is equal to x index(x) Return index of first item that is equal to x
  • 59. Tuple Membership Test • We can test if an item exists in a tuple or not, using the keyword in.
  • 60. Iterating Through a Tuple • Using a for loop we can iterate though each item in a tuple.
  • 61. Function Description all() Return True if all elements of the tuple are true (or if the tuple is empty). any() Return True if any element of the tuple is true. If the tuple is empty, return False. enumerate() Return an enumerate object. It contains the index and value of all the items of tuple as pairs. len() Return the length (the number of items) in the tuple. max() Return the largest item in the tuple. min() Return the smallest item in the tuple sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself). sum() Retrun the sum of all elements in the tuple. tuple() Convert an iterable (list, string, set, dictionary) to a tuple. Built-in Functions with Tuple
  • 63. Sets Definition: • Sets are used to store multiple items in a single variable. • Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary. • Syntax of set: where <iter> : iterable can be anything like list, tuple,etc. List and tuple are the other built-in data structures in python just like settings.
  • 64. Example: The other way to create a set in python is to define the elements in a set of curly braces: The syntax for the same is shown as follows:
  • 65. Exercise • Given a list of elements, remove the duplicate elements.
  • 66. Exercise • Read a string and find the number of unique characters in it.
  • 68. Sets • Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. • We can do this with operators or methods. Method Operator union | intersection & difference - symmetric_difference ^
  • 70. Operators 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 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
  • 74. Set Mutation Operations • We have seen the applications of union, intersection, difference and symmetric difference operations, but these operations do not make any changes or mutations to the set. • We can use the following operations to create mutations to a set: Method Operator update |= Update the set by adding elements from an iterable/another set. intersection_update &= Update the set by keeping only the elements found in it and an iterable/another set. Difference_update -= Update the set by removing elements found in an iterable/another set. symmetric_difference_update ^= Update the set by only keeping the elements found in either set, but not in both.
  • 75. Set Mutation Operations • Isdisjoint– This method will return True if two set have a null intersection • Issubset – This method reports whether another set contains this set • Issuperset – This method will report whether this set contains another set
  • 78. Python Dictionary: • In Python, a dictionary is a set of keys and values that can be used to store data values like a map, in contrast to other data types that can only contain a single value per element.
  • 79. More on Dictionary: • An unordered collection of elements is a Python dictionary. • In contrast to other compound data types, dictionaries include a key:value pair. • When the key is known, dictionaries are designed to retrieve values quickly.
  • 80. Creating a Dictionary: • By putting a series of components within curly brackets and separating them with a comma, one can create a dictionary in Python. • Dictionary has two equivalent pair elements, one of which is the Key and the other is its Key:value. • A dictionary's values can be of any data type and can be replicated, but its keys must be immutable and cannot be repeated. • Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
  • 81. Example: • marks = {“Maths” : 34, “Science” : 22 ,”English” :56} • print(marks) • xyz = {“Name” : ‘Tina’, 1:[2,4,1,7]} • print(xyz) • Dictionary = { } • print(“Empty Dictionary”,Dictionary)
  • 82. Inbuilt dict() function: • Dict = dict({1: ‘Apple', 2: ‘Andriod', 3: ‘Tablet'}) • print("nDictionary with the use of dict(): ") • print(Dict) • # Creating a Dictionary • # with each item as a Pair • Dict = dict([(1, ‘Lamborgini'), (2, ‘BMW')]) • print("nDictionary with each item as a pair: ") • print(Dict)
  • 83. Nested Dictionary: • # Creating a Nested Dictionary • DT = {1: 'Jain', 2: 'University', • 3: {'A': 'Welcome', 'B': 'To', 'C': 'SET'}} • print(DT)
  • 84. Adding element(s) to a Dictionary: • Multiple methods can be used to add items. • By defining the value and the key together, for example, Dict[Key] = "Value," one value can be added to a dictionary at a time. • Using the built-in update() method, one can modify an existing value in a Dictionary. • An existing Dictionary may also be expanded with nested key values. • Note: When adding a value, the value is updated if the key-value combination already exists. If not, a new key and value are added to the dictionary.
  • 85. Example: • # Adding elements one at a time • Dict[0] = 'Jain' • Dict[2] = 'University' • Dict[3] = 10 • print("nDictionary after adding 3 elements: ") • print(Dict)
  • 86. Example: • # Adding set of values to a single Key • Dict['Value_set'] = 24, 3, 43 • print("nDictionary after adding 3 elements: ") • print(Dict)
  • 87. Example: • # Adding Nested Key value to Dictionary • Dict[5] = {'Nested': {'1': 'Deemed', '2': 'To be University'}} • print("nAdding a Nested Key: ") • print(Dict)
  • 89. Accessing element of a Dictionary:
  • 91. Accessing an element of a nested dictionary
  • 92. Dictionary Methods: clear() Remove all the elements from the dictionary copy() Returns a copy of the dictionary get() Returns the value of specified key items() Returns a list containing a tuple for each key value pair keys() Returns a list containing dictionary’s keys pop() Remove the element with specified key
  • 93. popitem() Removes the last inserted key-value pair update() Updates dictionary with specified key- value pairs values() Returns a list of all the values of dictionary Dictionary Methods:
  • 94. Examples for all Dictionary Methods
  • 95. Examples for all Dictionary Methods
  • 97. Function Definition: • It is not advised to write a collection of statements separately if they are needed repeatedly. • These statements must be defined as one unit, which we can then call as many times as necessary to meet our requirements without having to rewrite anything. • Function alone defines this apparatus.
  • 98. Function Definition: • The main advantage of functions is code Reusability. • Note: In other languages, functions are known as methods, procedures, subroutines, etc. • Python supports 2 types of functions • Built In Functions • User DefinedFunctions
  • 99. Built In Functions: • Built-in or predefined functions refer to the functions that are automatically included with Python software. • id() • type() • input() • eval()
  • 100. User defined functions: • User defined functions are those that are explicitly developed by programmers in accordance with business requirements. • Syntax: • def function_name(parameters): • statements • return value Keywords
  • 101. Function Call • Once we have defined a function, we can call it from another function, program or even the Python prompt. • To call a function we simply type the function name with appropriate parameters. Calling the Function my_function()
  • 102. Example: WA Function to print “BE YOU,DO YOU ,FOR YOU
  • 103. Parameters: • The function's inputs are the parameters. • If a function has parameters, we must provide values at the time of calling; otherwise, we will receive an error.
  • 104. Write a function to get square of user input number:
  • 105. Return Statement: • Function can take input values as parameters and execute the logic, and return the output to the caller with return statement.
  • 106. Return Statement: • If we are not mentioning return statement, then default return value is None.
  • 107. Exercise: WA function to find whether the given number is even or odd:
  • 109. Scope and Lifetime of variables • Scope of a variable is the portion of a program where the variable is recognized. • Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope. • Lifetime of a variable is the period throughout which the variable exits in the memory.The lifetime of variables inside a function is as long as the function executes. • They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.
  • 110. Scope and Lifetime of variables
  • 111. Scope and Lifetime of variables
  • 112. Scope and Lifetime of variables
  • 113. Types of Arguments • There are 4 types are actual arguments are allowed In Python. • Positional Arguments • Keyword Arguments • Default Arguments • Variable length Arguments
  • 114. Positional Arguments: • These are the arguments passed to function in correct positional order. • The number of arguments and position of arguments must be matched. If we change the order then result may be changed and if number of arguments differ, then we will get error.
  • 116. Keyword Arguments: • We can pass argument values by keyword i.e, by parameter name. • Here the order of arguments is not important but number of arguments must be matched. • Note; We can use both positional and keyword arguments at the same time. But first we have to take positional arguments and then keyword arguments, else we will get syntaxerror.
  • 120. Default Arguments • Function arguments can have default values in Python. • We can provide a default value to an argument by using the assignment operator (=).
  • 121. Default Arguments: • In this function, the parameter amount does not have a default value and is required (mandatory) during a call. • On the other hand, the parameter discountPercentage has a default value of 0. So, it is optional during a call. • If a value is provided, it will overwrite the default value. • Any number of arguments in a function can have a default value.
  • 122. Default Arguments • Once we have a default argument, all the arguments to its right must also have default values. • SyntaxError: non-default argument follows default argument
  • 123. Variable Length Arguments: • Variable length arguments are those that we can occasionally supply to our function in a variable number. • The following symbol can be used to declare an argument of variable length: def func(*n): • Any number of parameters, even zero, may be sent to this function when calling it, and all of the values are internally represented as tuples.
  • 124. Variable number of arguments
  • 125. Functions as Objects • Although functions are created differently from normal variables, functions are just like any other kind of value. • They can be assigned and reassigned to variables, and later referenced by those names.
  • 127. Recursive Functions: • A function that calls itself is known as Recursive Function. • Advantages of recursive functions are: • We can reduce length of the code and improves readability. • We can solve complex problems very easily.
  • 129. Recursive Algorithms: • A recursive algorithm is an algorithm which calls itself with a smaller problem. • If a problem can be solved utilizing solutions to smaller versions of the same problem and the smaller versions reduce to easily solvable cases, then one can use a recursive algorithm to solve that problem. • They are of two types: indirect and direct recursion • Example :Code for determining if a given list contains a given string
  • 130. Search using recursive Algorithms:
  • 131. Recursive explorations of all possibility : • This is supposed to return a list back to the use with all the possible permutations. • Example :Code to return all possible permutation of string.
  • 132. Anonymous Function: • When a function is declared, it may not have a name. • These types of nameless functions are known as anonymous functions or lambda functions. • The anonymous function's primary use is only for one-time, instantaneous use.
  • 133. Lambda Function: • Lambda keyword lambda n:n•n allows us to define. • Lambda syntax • Expression: lambda argument list: function • Note: By using lambda functions, we may create extremely brief code, improving the readability of the program.
  • 134. Lambda Function: • Write a Program to create a Lambda Function to find Square of given Number?
  • 135. Sum of numbers using lambda: Find largest of numbers using lambda:
  • 136. Note • We are not required to write an explicit return statement because Lambda Functions return expression values internally. • It should be noted that functions can occasionally be passed as arguments to other functions. • The best option in these situations is lambda functions. • Due to the fact that filter(), map(), and reduce() expect a function as an argument, lambda functions are frequently used with these functions.
  • 137. filter() Function: • filter() function is used to filter values from the given sequence based on some condition. • filter(function(sequence)) • Where Function Argument is responsible to perform conditional check Sequence can be List OR Tuple OR String.
  • 139. Using lambda and filter():
  • 140. map() function: • Python’s map() function takes in a list and another function. • The function argument is called with all elements in the list and returns a new list containing elements returned from each element in the original list. • Syntax: map(function,sequence)
  • 142. With lambda and map():
  • 143. reduce() function: • reduce() function reduces the sequence of elements Into a single element by applying the specified function. • Syntax: reduce(function, sequence) • reduce() function is present in functools module and hence we should write import statement.
  • 144.
  • 145. eval() function: • This will allows you to evaluate arbitrary Python expressions from a string-based or compiled- code-based. • This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object. • Syntax of eval()
  • 146.
  • 147. zip() function: • zip() function returns a zip object. • This is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc. • Syntax of zip()
  • 149. Cartesian Product: • Suppose we have 2 list of data list1 and list2. • To find the cartesian product of (a,b) and (c,d) = {(a,c),(a,d),(b,c),(b,d)} • To find this , we will use the itertools library and product function which is present in this library.
  • 150. exec() function: • The exec() function is used to execute Python program dynamically. • These program can either be strings or object code. • If it's a string, it's translated into a series of Python statements that are then performed, barring any syntax errors; if it's object code, it's just executed. • Using return statements outside of function declarations, not even in the context of code provided to the exec() method, requires caution. • It returns None since it has no value to return.
  • 152. copy() function: • The copy() method returns a copy of the list.
  • 153. enumerate(): • Returns an enumerate object which contains the value and index of all list elements as tuple. • Returns an enumerate object which contains the value and index of all set elements as a pair. • Returns an enumerate object containing the value and index of all tuple elements as pairs.
  • 155. List Comprehensions: • It is very easy and compact way of creating list objects from any lterableobjects (like list,Tuple, Dictionary, Range.etc) based on some condition. • Syntax: • list=[expression for elements in list if conditions]
  • 157. LIST Vs TUPLE Vs SETS: List Tuple Set Lists is Mutable Tuple is Immutable Set is Mutable It is Ordered collection of items It is Ordered collection of items It is Unordered collection of items Items in list can be replaced or changed Items in tuple cannot be changed or replaced Items in set cannot be changed or replaced
  • 158. Mutable: • When anything can be altered or changed, it is said to be mutable. The term "mutable" in Python refers to an object's capacity to modify its values. These are frequently the things that hold a data collection. • Immutable: Immutable refers to a state in which no change can occur over time. An object is referred to as immutable in Python if its value cannot change over time. The worth of these things is fixed once they are made.
  • 159. Adding output comment for debugging: • The logging module has everything. • Its recommend using logging.basicConfig to toggle the logging level to stderr and the simple log methods, debug, info, warning, error and critical. • Code sample below is used for logging: •
  • 160. Terminal Questions 1. Write a Python function that takes a list of integers as input and returns a new list containing only the even numbers from the original list. 2. Given a dictionary of student names and their corresponding grades, write a function that takes the dictionary as input and returns the names of students who have scored above a certain grade threshold (e.g., 80).
  • 161. Reference 1. Lutz, Mark (2013). Learning Python (5th ed.). O'Reilly Media. 2. https://www.w3schools.com/python/python_intro.asp 3. https://www.geeksforgeeks.org/python-programming-language/ 4. https://docs.python.org/3/tutorial/index.html 5. https://www.javatpoint.com/python-tutorial 6. https://www.coursera.org/learn/python-programming-intro 7. https://www.javatpoint.com/python-tutorial