0% found this document useful (0 votes)
3 views73 pages

Python Chap3 (5)

Uploaded by

abhishekmane280
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
3 views73 pages

Python Chap3 (5)

Uploaded by

abhishekmane280
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 73

Chapter 3

Lists, functions, tuples and


dictionaries, Sets
• Python Lists: Concept, creating and accessing elements, updating & deleting lists,
traversing a List, reverse Built-in List Operators, Concatenation, Repetition, In
Operator, Built-in List functions and methods.
• Functions: Definitions and Uses, Function Calls, Type Conversion Functions,
Math Functions, Composition, Adding New Functions, Flow of Execution, Parameters
and Arguments, Variables and Parameters, Stack Diagrams, Void Functions,
Anonymous functions Importing with from, Return Values, Boolean Functions, More
Recursion, Functional programming tools - filter(), map(), and reduce(),recursion, lambda
forms.
• Tuples and Dictionaries: Tuples, Accessing values in Tuples, Tuple Assignment, Tuples
as return values, Variable-length argument tuples, and Basic tuples operations,
Concatenation, Repetition, in Operator, Iteration, Built-in tuple functions, indexing,
slicing and matrices.
• Creating a Dictionary, Accessing Values in a dictionary, Updating Dictionary, Deleting
Elements from Dictionary, Properties of Dictionary keys, Operations in Dictionary, Built-
In Dictionary Functions, Built-in Dictionary Methods.
• Sets- Definition, transaction of set(Adding, Union, intersection), working with sets
Lists
• Lists are just like dynamically sized arrays, declared in other languages (vector
in C++ and ArrayList in Java).
• 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.
• List in Python are ordered and have a definite count. The elements in a list are
indexed according to a definite sequence and the indexing of a list is done
with 0 being the first index.
• Each element in the list has its definite place in the list, which allows
duplicating of elements in the list, with each element having its own distinct
place and credibility.
• Lists are a useful tool for preserving a sequence of data and further iterating
over it.
• Creating a List
• 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 the creation of a list.
• Unlike Sets, the list may contain mutable elements.

• Example
# Creating Blank List
List = []
print("Blank List: ")
print(List)
• Output
• Blank List:
[]
• Example • Example
# Creating a List of # Creating a List of
numbers strings and accessing
List = [10, 20, 14] # using index
print("\nList of numbers:
") List = ["Green",
"For", "Gorge"]
print(List)
• Output print("\nList Items: ")
• List of numbers: print(List[0])
[10, 20, 14] print(List[2])
• Output
List Items
Green
Gorge
• Example
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Green', 'For'] , ['Trees']]
print("\nMulti-Dimensional List: ")
print(List)

• Output
• Multi-Dimensional List:
[['Green', 'For'], ['Trees']]
• Accessing elements from the List • Example
• In order to access the list items refer to the #Creating a Multi-Dimensional
index number. Use the index operator [ ] to List
access an item in a list. The index must be an
integer. Nested lists are accessed using # (By Nesting a list inside a
nested indexing. List)
List = [['Green', 'For'] ,
• Example ['George']]
• List = ["Green", "For", print("Accessing a element from
"George"] a Multi-Dimensional list")
• print("Accessing a element from print(List[0][1])
the list")
print(List[1][0])
• print(List[0])
• print(List[2]) Output
• Output Accessing a element from a
• Accessing a element from the
Multi-Dimensional list
list For
• Green George
• Knowing the size of List
• Example
# Creating a List
List1 = []
print(len(List1))

# Creating a List of numbers


List2 = [10, 20, 14]
print(len(List2))

• Output:
•0
3
• Adding Elements to a List
• Using append() method
Elements can be added to the List by using the built-in append() function. Only one element
at a time can be added to the list by using the append() method, for the addition of multiple
elements with the append() method, loops are used. Tuples can also be added to the list with
the use of the append method because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of the append() method.
• Example
List = []
print("Initial blank List: ")
print(List)

• Output
Initial blank List:
[]
• Example 2
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

• output
List after Addition of Three elements:
[1, 2, 4]
# Addition of List to a List
List2 = ['Red', 'Green']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

• Output
• List after Addition of a List:
[1, 2, 4, ['Red', 'Green']]
• Using insert() method
• append() method only works for the addition of elements at the end of the
List, for the addition of elements at the desired position, insert() method is
used. Unlike append() which takes only one argument, the insert() method
requires two arguments(position, value).

# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
• Output
• Initial List:
• [1, 2, 3, 4]
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Green')
print("\nList after performing Insert Operation: ")
print(List)

• output
• List after performing Insert Operation:
• ['Green', 1, 2, 3, 12, 4]
• Using extend() method
• Other than append() and insert() methods, there’s one more method for the Addition of elements,
extend(), this method is used to add multiple elements at the same time at the end of the list.
Note – append() and extend() methods can only add elements at the end.
• Example
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.extend([8, 'Green', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
• Output
• Initial List:
• [1, 2, 3, 4]

• List after performing Extend Operation:
• Removing Elements from the List
1. Using remove() method
• Elements can be removed from the List by using the built-in remove() function but an Error arises if the
element doesn’t exist in the set. 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
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)
• Output
• Initial List:
• [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

• List after Removal of two elements:
• Example
# Removing elements from List
# using iterator method
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)

• output
• List after Removing a range of elements:
• [7, 8, 9, 10, 11, 12]
2.Using pop() method
• Pop() function can also be used to remove and return an element from the set, but by default it removes only the
last element of the set, 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.
• Example
List = [1,2,3,4,5]
List.pop()
print("\nList after popping an element: ")
print(List)

List.pop(2)
print("\nList after popping a specific element: ")
print(List)

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

• List after popping a specific element:
[1, 2, 4]
• List Comprehension
• 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.
• Example
# comprehension in Python
# below list contains square of all
# odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print (odd_square)
• Output:
[1, 9, 25, 49, 81]
List Methods
Function Description

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

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

Insert() Insert an item at the defined index

Remove() Removes an item from the list

Pop() Removes and returns an element at the given index

Clear() Removes all items from the list

Index() Returns the index of the first matched item

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

Sort() Sort items in a list in ascending order

Reverse() Reverse the order of items in the list

copy() Returns a copy of the list


Built-in functions with List
Function Description

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

sum() Sums up the numbers in the list

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

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

max() return maximum element of a given list

min() return minimum element of a given list

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

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

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


Built-in functions with List

enumerate()​ Returns enumerate object of the list​

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

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

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

This function can have any number of arguments but only one expression, which is
lambda()​ evaluated and returned.​
Tuples
• A tuple in Python is similar to a list.
• A Tuple is immutable. we cannot change the elements of a tuple once it is
assigned whereas we can change the elements of a list.

• Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.
A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).
• Examples • Output
• # Empty tuple • ()
• my_tuple = () • (1, 2, 3)
• print(my_tuple) • (1, 'Hello', 3.4)
• ('mouse', [8, 4, 6], (1, 2,
• # Tuple having integers 3))
• my_tuple = (1, 2, 3)
• print(my_tuple)

• # tuple with mixed
datatypes
• my_tuple = (1, "Hello",
3.4)
• print(my_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.
• my_tuple = ("hello")
print(type(my_tuple))

# Creating a tuple having one element


my_tuple = ("hello",)
print(type(my_tuple))

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
<class 'str'>
<class 'tuple'>
• <class 'tuple'>
• A tuple can also be created without using parentheses. This is known as tuple
packing.
• Example
• my_tuple = 3, 4.6, "dog"
• print(my_tuple)

• # tuple unpacking is also possible
• a, b, c = my_tuple
• print(a)
• print(b)
print(c)
• Output
• (3, 4.6, 'dog')
•3
• Access Tuple Elements
• There are various ways in which we can access the elements of a tuple.
• 1. Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
• Output
• p
• t
• s
• 4
• 2. Negative Indexing • 3. Slicing
• Python allows negative indexing • We can access a range of items in
for its sequences. a tuple by using the slicing
• The index of -1 refers to the last operator colon :
item, -2 to the second last item • my_tuple =
and so on. ('p','r','o','g','r','a
• Example ','m','i','z')
• my_tuple = ('p', 'e', 'r', 'm', •
'i', 't') • print(my_tuple[1:4])
• print(my_tuple[-1]) •
print(my_tuple[-6]) • print(my_tuple[:-7])
• Output • Output
•t • ('r', 'o', 'g')
p ('p', 'r')
• Changing a Tuple
• Unlike lists, tuples are immutable. But, if the element is itself a mutable data type like a list,
its nested items can be changed.
• We can also assign a tuple to different values (reassignment).
• Examples
• my_tuple = (4, 2, 3, [6, 5])
• my_tuple[1] = 9
• # This statement error as TypeError: 'tuple' object does not
support item assignment
my_tuple[3][0] = 9
print(my_tuple)
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
• output
• (4, 2, 3, [9, 5])
• Deleting a Tuple
• As discussed above, we cannot change the elements in a tuple. It means that we cannot
delete or remove items from a tuple.
• Deleting a tuple entirely, however, is possible using the keyword del
• Example
• my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
• del my_tuple[3]
• # Above statement gives error as TypeError: 'tuple'
object doesn't support item deletion
• del my_tuple
print(my_tuple)
• Output
• Traceback (most recent call last):
• File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined
• Finding Length of a Tuple
• Example
tuple2 = ('python', 'Prog')
print(len(tuple2))
• Output
2

• Converting list to a Tuple


Takes 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.
• Example
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python'))
• Output
• (0, 1, 2)
• Concatenation and repeat

• We can use + operator to combine two tuples. This is called concatenation.


• We can also repeat the elements in a tuple for a given number of times using
the * operator.
• Both + and * operations result in a new tuple.
• examples
• print((1, 2, 3) + (4, 5, 6))
• print(("Repeat",) * 3)
• output
• (1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
• Tuple Methods
• Methods that add items or remove items are not available with tuple. Only
the following two methods are available.
• Some Python tuple methods:
• examples
• my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p'))
print(my_tuple.index('l'))
• output
•2
3
Tuple Membership Test
• We can test if an item exists in a tuple or not, using the keyword in.
• Example
• my_tuple = ('a', 'p', 'p', 'l', 'e',)

• print('a' in my_tuple)
• print('b' in my_tuple)
• print('g' not in my_tuple)
• Output
• True
• False
True
• Using max() , min()
• Python tuple method max() returns the elements from the tuple with
maximum value.
• Python tuple method min() returns the elements from the tuple with
minimum value.
• Example
• t1=(1,2,3)
• t2=(4,5,6,7)
• print(max(t1))
• print(min(t1))
• Output
•3
•1
Set
• A Set is an unordered collection data type that is iterable. Since sets are
unordered, we cannot access items using indexes like we do in lists.
• mutable and has no duplicate elements.
• Python’s set class represents the mathematical notion of a set.
• 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.
• Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
• set cannot have duplicate • set cannot have mutable
• Example items
• my_set = {1, 2, 3, 4, 3, • Example
2} my_set = {1, 2, [3, 4]}
• print(my_set)
• Output • Output (Error)
• {1, 2, 3, 4} • Traceback (most recent
call last):
• make set from a list File "<string>", line
15, in <module>
• Example
my_set = {1, 2, [3,
• my_set = set([1, 2, 3, 2]) 4]}
print(my_set) TypeError: unhashable ty
• Output pe: 'list'
{1, 2, 3}
• Creating Python Sets
• A set is created by placing all the items (elements) inside curly braces {}, separated
by comma, or by using the built-in set() function.
• It can have any number of items and they may be of different types (integer, float,
tuple, string etc.).
• But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
• Example
• my_set = {1, 2, 3}
• print(my_set)

• # set of mixed datatypes
• my_set = {1.0, "Hello", (1, 2, 3)}
• print(my_set)
• Output
• Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements, we use the set() function without any argument.
Example1
a = {}
• print(type(a))
• Output
• <class 'dict'>

• Example2
• a = set()
print(type(a))
• Output
<class 'set'>
• Methods for Sets
• Adding elements With add() method
• Insertion in set is done through set.add() function, if member is not present
and inserted where an appropriate record value is created to store in the hash
table.
• We can add a single element using the add() method

• Adding elements With update() method


• It can add multiple elements using the update() method.
• The update() method can take tuples, lists, strings or other sets
as its argument. In all cases, duplicates are avoided.
• Example
• my_set = {1, 3}
print(my_set)
my_set.add(2)
print(my_set)
my_set.update([2, 3, 4])
print(my_set)
my_set.update([4, 5], {1, 6, 8})
print(my_set)
• Output
• {1, 3}
• {1, 2, 3}
• {1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
• Removing elements from a set my_set.remove(6)
print(my_set)
• A particular item can be removed from a set using the
methods discard() and remove(). my_set.discard(2)
• The only difference between the two is that print(my_set)
the discard() function leaves a set unchanged if my_set.remove(2)
the element is not present in the set.
• On the other hand, the remove() function will raise • Output
an error in such a condition (if element is not present • {1, 3, 4, 5, 6}
in the set). • {1, 3, 5, 6}
• Example • {1, 3, 5}
• my_set = {1, 3, 4, 5, 6} • {1, 3, 5}

• print(my_set)
Error : Traceback (most
• recent call last):
• my_set.discard(4) File "<string>", line
28, in <module>
• print(my_set) KeyError: 2
• Removing using Clear() Method
• We can also remove all the items from a set using the clear() method.
• Example
s1={3,4,5}
s1.clear()
print(s1)
• Output
set()
• Python Set Operations
• 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.
• Set Union
• Union of A and B is a set of all elements from both sets.
• Union is performed using | operator. Same can be accomplished using
the union() method.
• Example 1 Union by using Operator
s1={2,3,4}
s2={4,5,6}
print(s1|s2)
• Output
{2, 3, 4, 5, 6}
• Example2 By using Union() Method
s1={2,3,4,9}
s2={4,5,6,7}
print(s1.union(s2))
• Output
{2, 3, 4, 5, 6, 7, 9}
• Set Intersection • Example1 By using
• Intersection of A and B is a set of intersection() Method
elements that are common in both s1={2,3,4,6,9}
the sets. s2={5,6,7}
• Intersection is performed print(s1.intersection(s2))
using & operator. Same can be
• Output
accomplished
using the intersection() metho {6}
d.
• Example1 By using operator &
s1={2,3,4,9}
s2={4,5,6,7}
print(s1&s2)
• Output
{4}
• Set Difference • Example 2
• Difference of the set B from set A (A - B) is a s1={1,2,3,4,5}
set of elements that are only in A but not in B.
s2={4,5,7,8}
Similarly, B - A is a set of elements in B but not
in A. print(s2-s1)
• Difference is performed using - operator. • Output
Same can be accomplished using {8, 7}
the difference() method. • Example3
• Example1
s1={1,2,3,4,5}
s1={1,2,3,4,5} s2={4,5,7,8}
s2={4,5,8} print(s1.difference(s2))
print(s1-s2) • Output
• Output
{1, 2, 3}
{1, 2, 3}
• Set Symmetric Difference • Example 2
• Symmetric Difference of A and B is a set of s1={1,2,3,4,5}
elements in A and B but not in both
(excluding the intersection). s2={4,5,7,8}
• Symmetric difference is performed print(s1.symmetric_difference(s2))
using ^ operator. Same can be • Output
accomplished using the {1, 2, 3, 7, 8}
method symmetric_difference().
• Example 1
• s1={1,2,3,4,5}
• s2={4,5,7,8}
• print(s1^s2)
• Output
• {1, 2, 3, 7, 8}
• Operators for Sets Operators Notes

key in s containment check

key not in s non-containment check

s1 == s2 s1 is equivalent to s2

s1 != s2 s1 is not equivalent to s2

s1 <= s2 s1 is subset of s2

s1 < s2 s1 is proper subset of s2

s1 >= s2 s1 is superset of s2

s1 > s2 s1 is proper superset of s2

s1 | s2 the union of s1 and s2

s1 & s2 the intersection of s1 and s2

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

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


• Other Python Set Methods
Function Description

all() Returns True if all elements of the set are true (or if the set is empty).

any() Returns True if any element of the set is true. If the set is empty, returns False.

Returns an enumerate object. It contains the index and value for all the items of the set as
enumerate()
a pair.

len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

sorted() Returns a new sorted list from elements in the set(does not sort the set itself).

sum() Returns the sum of all elements in the set.


• Python Frozenset
• Frozenset is a new class that has the characteristics of a set, but its elements
cannot be changed once assigned. While tuples are immutable lists, frozensets
are immutable sets.
• Sets being mutable are unhashable, so they can't be used as dictionary keys. On
the other hand, frozensets are hashable and can be used as keys to a dictionary.
• Frozensets can be created using the frozenset() function.
• This data type supports methods
lcopy(), difference(), intersection(), isdisjoint(), issubse
t(), issuperset(), symmetric_difference() and union(). Being
immutable, it does not have methods that add or remove elements.
Python Dictionary

• Dictionary in Python is an unordered collection of data values, used to store


data values like a map, which, unlike other Data Types that hold only a single
value as an element, Dictionary holds key:value pair. Key-value is provided in
the dictionary to make it more optimized.
• Dictionaries are mutable.
• Creating Python Dictionary
• Creating a dictionary is as simple as placing items inside curly
braces {} separated by commas.
• An item has a key and a corresponding value that is expressed as a pair
(key: value).
• While the values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements) and must
be unique.
#empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


• Accessing Elements from Dictionary

• While indexing is used with other data types to access values, a dictionary
uses keys. Keys can be used either inside square brackets [] or with
the get() method.

• If we use the square brackets [], KeyError is raised in case a key is not
found in the dictionary. On the other hand, the get() method
returns None if the key is not found.


• Examples

my_dict = {'name': 'Jack', 'age': 26}


print(my_dict['name'])
print(my_dict.get('age'))
print(my_dict.get('address'))
print(my_dict['address'])

• Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
• Examples
Dict = {1: 'Green', 2: 'For', 3:{'A' : 'Welcome', 'B' :
'To', 'C' : 'Germany'}}
• print(Dict)

• OutPut
{1: 'Green', 2: 'For', 3: {'A': 'Welcome', 'B': 'To',
'C': 'Germany'}}
• Changing and Adding Dictionary elements

• Dictionaries are mutable. We can add new items or change the value of
existing items using an assignment operator.

• If the key is already present, then the existing value gets updated. In case the
key is not present, a new (key: value) pair is added to the dictionary.
• Example • Output
• my_dict = {'name': 'Jack', • {'name': 'Jack', 'age':
'age': 26} 27}
• {'name': 'Jack', 'age':
• my_dict['age'] = 27 27, 'address':
'Downtown'}

• print(my_dict)

• my_dict['address'] =
'Downtown'

print(my_dict)
• Removing elements from Dictionary
• We can remove a particular item in a dictionary by using the pop() method.
This method removes an item with the provided key and returns the value.
• The popitem() method can be used to remove and return an
arbitrary (key, value) item pair from the dictionary. All the items can be
removed at once, using the clear() method.
• We can also use the del keyword to remove individual items or the entire
dictionary itself.
Examples
• Output
squares = {1: 1, 2: 4, 3: • 16
9, 4: 16, 5: 25}
• {1: 1, 2: 4, 3: 9, 5:
25}
print(squares.pop(4)) • (5, 25)
• {1: 1, 2: 4, 3: 9}
print(squares) • {}
• Traceback (most recent
print(squares.popitem()) call last):
• File "<string>", line
30, in <module>
print(squares)
• print(squares)
NameError: name 'squares'
squares.clear()
is not defined
• Python Dictionary Comprehension
• Dictionary comprehension is an elegant and concise way to create a new dictionary from an
iterable in Python.
• Dictionary comprehension consists of an expression pair (key: value) followed by
a for statement inside curly braces {}.
• Here is an example to make a dictionary with each item being a pair of a number and its square.
• Example
• squares = {x: x*x for x in range(6)}
• print(squares)
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
• Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
• Dictionary Membership Test
• We can test if a key is in a dictionary or not using the keyword in. Notice that the
membership test is only for the keys and not for the values.
• Example
• squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

• print(1 in squares)

• print(2 not in squares)

• print(49 in squares)
• Output
• True
• True
False
• Iterating Through a Dictionary
• We can iterate through each key in a dictionary using a for loop.
• Example
• squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
• for i in squares:
• print(squares[i])
• Output
•1
•9
• 25
• 49
81
• Python Dictionary Methods
Method Description

clear() Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.

fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).

get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).

items() Return a new object of the dictionary's items in (key, value) format.

keys() Returns a new object of the dictionary's keys.

Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not
pop(key[,d])
found, it raises KeyError.

popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.

Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d
setdefault(key[,d])
(defaults to None).

update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.

values() Returns a new object of the dictionary's values


• Dictionary Built-in Functions

Function Description

all() Return True if all keys of the dictionary are True (or if the dictionary is empty).

any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries. (Not available in Python 3)

sorted() Return a new sorted list of keys in the dictionary.


Functions in Python
• Python Functions is a block of related statements designed to perform a
computational, logical, or evaluative task.
• The idea is to put some commonly or repeatedly done tasks together and
make a function so that instead of writing the same code again and again for
different inputs, we can do the function calls to reuse code contained in it over
and over again.
• Functions can be both built-in or user-defined. It helps the program to be
concise, non-repetitive, and organized.
• Syntax:
• def function_name(parameters):
• """docstring"""
• statement(s)
• return expression
• Above shown is a function definition that consists of the following
components.
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming follows
the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They
are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the function
does.
• One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.
• Docstring
• The first string after the function is called the Document string or Docstring in short. This is used
to describe the functionality of the function. The use of docstring in functions is optional but it is
considered a good practice.
• The below syntax can be used to print out the docstring of a function:
• Syntax: print(function_name.__doc__)
• Example
def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")
print(evenOdd.__doc__)
• Output
Function to check if the number is even or odd
• The return statement
• The function return statement is used to exit from a function and go back to the function caller
and return the specified value or data item to the caller.
• Syntax: return [expression_list]
• The return statement can consist of a variable, an expression, or a constant which is returned to
the end of the function execution. If none of the above is present with the return statement a
None object is returned.
• Example
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
• Output
• 4
16
• Creating a Function
• We can create a Python function using the def keyword.
• Calling a Function
• After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.
• Example
def fun():
print("Welcome to Python World")
fun()
• Output
Welcome to Python World
• Arguments of a Function
• Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.
• Example: Python Function with arguments
• In this example, we will create a simple function to check whether the number passed as an
argument to the function is even or odd.
Example :
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output :
even
• 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 are not visible from outside the function. Hence, they have a local
scope.
• The lifetime of a variable is the period throughout which the variable exists 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.
• Example
• def my_func():
• x = 10
• print("Value inside function:",x)
• x = 20
• my_func()
print("Value outside function:",x)
• Output
• Value inside function: 10
• Anonymous functions :
• In Python, an anonymous function means that a function is without a name.
As we already know the def keyword is used to define the normal functions
and the lambda keyword is used to create anonymous functions. Please see
this for details.
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))
• Output
• 343
• Python Function within Functions
• A function that is defined inside another function is known as the inner function or
nested function. Nested functions are able to access variables of the enclosing
scope. Inner functions are used so that they can be protected from everything
happening outside the function.
• Example
def f1():
s = 'welcome'
def f2():
print(s)

f2()
f1()
• Output
welcome

You might also like