6. Where Python is used?
Wait! I can do all these things using
other programming languages too! Then
why Python?
6
7. Why Python?
Solves complex problems in less time with fewer
lines of code.
Hello World
str = 'Hello world’
print(str[0:3])
Hel
7
8. Why Python?
Python is a multi-purpose language with a simple,
and beginner-friendly syntax.
8
9. So, What we learned so far?
Python is a high-level, interpreted, interactive and
object-oriented scripting language.
Python was designed to be highly readable which uses
English keywords frequently where as other languages
use punctuation and it has fewer syntactical
constructions than other languages.
9
10. So, What we learned so far?
Python is interpreted: Processed at run time by the
interpreter, no need to compile the program before
executing it.
Python is Interactive: It means we can actually sit at a
python prompt and interact with the interpreter directly to
write programs
Python is Object-Oriented: Supports OOP that
encapsulates code within objects
Python is Beginner's Language: It is great language for
beginner programmers and supports the development of a
wide range of applications. 10
12. Hello world program in Java
public class HelloWorld
{
public static void main(String[ ] args)
{
System.out.println("Hello World");
}
}
Hello world program in Python
print(“Hello World”)
12
13. Hello Python
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
print("Hello world")
str=“Hello world”
print(str)
print(str[0:3])
Hello world
Hello world
Hel 13
25. Java vs Python
Parameter Java Python
Compilation Java is a Compiled Language
Python is an Interpreted
Language
Static or Dynamic Java is statically typed
Python is dynamically
typed
String operations
Offers limited string related
functions.
It offers lots of string
related functions.
Learning curve Complex learning curve Easy to learn and use
Multiple inheritances
Multiple inheritances is
partially done through
interfaces.
It offers both single and
multiple inheritances.
Braces vs. Indentation
It uses curly braces to define
the beginning and end of each
function and class definition.
Python uses indentation to
separate code into code
blocks.
25
26. Java vs Python
Parameter Java Python
Portability
Any computer or mobile device
which is able to run the Java virtual
machine can run a Java application
Python programs need an interpreter
installed on the target machine to
translate Python code. Compared to
Java, Python is less portable.
Read file
Java takes 10 lines of code to read
from a file in Java.
Python only needs 2 lines of code.
Architecture
Java Virtual Machine provides the
runtime environment to execute the
code and convert bytecode into
machine language.
For Python, the interpreter translates
source code into machine-
independent bytecode.
26
27. Java vs Python
Parameter Java Python
Best use
for
Java is best for Desktop GUI apps, Embed
Systems, Web application services, etc.
Python is excellent for scientific
and numeric computing, Machine
learning apps, more.
Database
support
Java offers stable connectivity Python offers weak connectivity.
Code
example
class A
{
public static void main(String args[ ])
{
System.out.println("Hello World");
}
}
print (“hello world”);
27
28. Java vs Python
Disadvantages of Java
JIT (Just In Time) compiler makes the program comparatively slow.
Java has high memory and processing requirements. Therefore,
hardware cost increases.
It does not provide support for low-level programming constructs like
pointers.
You don't have any control over garbage collection as Java does not
offer functions like delete( ), free( ).
28
29. Java vs Python
Disadvantages of Python
Used in fewer platforms.
Python is interpreted, so it's much slower than its counterparts.
Weak in mobile computing, hence not used in app development
Since Python is dynamic, more errors show up at run-time
Absence of commercial support
29
30. Comments
#This line is commented and won’t be executed
“““
This (“““ ”””) is called as docstring.
Docstring can act as a multiline comment
in Python after few lines of code.
”””
Please note: The recommended method for commenting multiple lines is
using # on each line. The (“””) method isn’t actually a comment but defines
a Text constant of the text between the (“””). It isn’t displayed, but exists
and could potentially cause unexpected errors. 30
31. Programming Assignment
Print your name.
Declare two variables (a , b) and assign values.
Print the results of the following
1. Addition of two numbers
2. Subtraction of two numbers
3. Multiplication of two numbers
4. Division of two numbers
Swap the numbers
Print the values of a and b after swapping
Submit the screenshot.
31
34. Data Types - Identifiers and Keywords
Python Identifiers : An identifier is a name given to
entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
34
35. Data Types - Identifiers and Keywords
100 x 5 =500
5 x 5 = 25
500 – 25=475
100*5-5*5
No_Honey_Cake_Made=100
Profit_on_each_cake=5
Unsold_cake=5
Profit=No_Honey_Cake_Made*Profit_on_each_cake-Unsold_cake*Profit_on_each_cake35
36. Data Types - Identifiers and Keywords
Operator precedence :
( )
* /
+ -
* and / or + and -
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5 = 90
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5=90
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d); # ________=__
print("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # ______=__
print ("Value of a + (b * c) / d is ", e)36
37. Data Types - Identifiers and Keywords
Rules for writing identifiers
1. Identifiers can be a combination of
Lowercase (a to z)
Uppercase (A to Z)
Digits (0 to 9)
An underscore _
Examples: myClass, var_1, print_this_to_screen.
2. An identifier cannot start with a digit.
Example: 1variable is invalid, but variable1 is a valid
2. Keywords cannot be used as identifiers.
3. We cannot use special symbols like !, @, #, $, % etc. in our
identifier.
4. An identifier can be of any length.
37
38. Data Types - Identifiers and Keywords
Things to Remember
Python is a case-sensitive language. This means, Variable and
variable are not the same.
Always give the identifiers a name that makes sense. While c
= 10 is a valid name, writing count = 10 would make more sense,
and it would be easier to figure out what it represents when you
look at your code after a long gap.
Multiple words can be separated using an underscore, like
this_is_a_long_variable.
38
39. Data Types - Identifiers and Keywords
Python Keywords : Keywords are the reserved words in
Python.
1. We cannot use a keyword as a variable name, function name
or any other identifier. They are used to define the syntax and
structure of the Python language.
2. There are 35 keywords in Python 3.7. This number can vary
slightly over the course of time.
3. In Python, keywords are case sensitive.
4. All the keywords except True, False and None are in
lowercase and they must be written as they are. The list of all
the keywords is given below. 39
40. Data Types - Identifiers and Keywords
Keywords in python
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
40
44. Data Types
Integers
Python interprets a sequence of decimal digits without any prefix
to be a decimal number.
Prefix Interpretation Base
0b (zero + lowercase letter 'b')
0B (zero + uppercase letter 'B')
Binary 2
0o (zero + lowercase letter 'o')
0O (zero + uppercase letter 'O')
Octal 8
0x (zero + lowercase letter 'x')
0X (zero + uppercase letter 'X')
Hexadecimal 16
44
45. Data Types
Floating point types
The float type in Python designates a
floating-point number. float values are
specified with a decimal point.
Optionally, the character e or E
followed by a positive or negative
integer may be appended to specify
scientific notation:
Complex Numbers
Complex numbers are specified as
<real part>+<imaginary part>j.
Example: 2+3j
45
46. Data Types
Strings
Strings are sequences of character data.
‘within single quotes’
“within double quotes”
A string in Python can contain as many characters as you wish. The only
limit is your machine’s memory resources. A string can also be empty:
What if you want to include a quote character as part of the string itself?
Use escape sequence.
Ex: print("It's my life ") It's my life
Ex: print("The "Honey Cake" is delicious") "Honey Cake" is delicious
46
51. Data Types
Assignment
Write a python program using only 4 print statements to get the result as
shown below
Expected output
It’s my Life
The “Birthday cake” was delicious
Give me my space
My_Name Register_No
PJC Final Year
JNC 51
52. Data Types
Assignment
Write a python program using only 4 print statements to get the result as
shown below
Program
print("It's my Life")
print("The "Birthday cake" was delicious")
print("Give me my tt space")
print("My_Name t t 18PJC001 nPJC Final Year nJNC")52
53. Content: Unit I
3. Collection data types:
Sequence types.
Set types
Mapping types
Iterating and Copying collections.
53
54. Collection of data types
Group of items Collections
Collections has four types
tuple
list
Set
Dictionary
Python tuples and lists can be used to hold any number of data items of
any data types.
Tuples are immutable, so once they are created we cannot change
them.
Lists are mutable, so we can easily insert items and remove items
whenever we want.
54
56. Collection of data types
Some of the operations common for both tuple and list are as follows −
S.No. Operation/Functions & Description
1 x in seq
True, when x is found in the sequence seq, otherwise False
2 x not in seq
False, when x is found in the sequence seq, otherwise True
3 x + y
Concatenate two sequences x and y
4 x * n or n * x
Replicate sequence x with itself n times
5 seq[i]
ith item of the sequence.
6 seq[i:j]
Slice sequence from index i to j
56
57. Collection of data types
Some of the operations common for both tuple and list are as follows −
S.No. Operation/Functions & Description
7 seq[i:j:k]
Slice sequence from index i to j with step k
8 len(seq)
Length or number of elements in the sequence
9 min(seq)
Minimum element in the sequence
10 max(seq)
Maximum element in the sequence
11 seq.count(x)
Count total number of elements in the sequence
57
58. Collection of data types
Some of the operations applicable for list are as follows −
S.No. Operation/Functions & Description
1 seq.append(x)
Add x at the end of the sequence
2 seq.clear()
Clear the contents of the sequence
3 seq.insert(i, x)
Insert x at the position i
4 seq.pop([i])
Return the item at position i, and also remove it from sequence. Default is last element.
5 seq.remove(x)
Remove first occurrence of item x
6 seq.reverse()
Reverse the list
58
59. Collection of data types
Tuple in Python
A tuple is a collection of objects which ordered and immutable.
Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use
square brackets.
59
60. Collection of data types
Creating a tuple is as simple as putting different comma-separated
values. Optionally you can put these comma-separated values between
parentheses also. For example −
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5 )
tuple3 = "a", "b", "c", “d”
The empty tuple is written as two parentheses containing nothing −
tuple0=( )
To write a tuple containing a single value you have to include a comma,
even though there is only one value −
tup1 = (50,) 60
61. Collection of data types
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain value available at that index.
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5 )
tuple3 = "a", "b", "c", "d","e"
print(tuple1[1:2]) # (‘chemistry’,)
print(tuple2[1:3]) # (2,3)
print(tuple3[1:4]) # (‘b’,’c’,’d’) 61
62. Collection of data types
Updating Tuples
Tuples are immutable which means you cannot update or change the
values of tuple elements. You are able to take portions of existing
tuples to create new tuples as the following example demonstrates
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5 )
tuple3 = "a", "b", "c", "d","e"
tuple1.append(2020)
tuple1.pop()
tuple1.remove(1997)
tuple4=tuple2+tuple3[2:3] # (1,2,3,4,5, ‘c’)
62
63. Collection of data types
Delete Tuple Elements
Removing individual tuple elements is not possible.
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5 )
tuple3 = "a", "b", "c", "d","e"
tuple4=tuple2+tuple3[2:3] # (1,2,3,4,5, ‘c’)
del tuple4
print(tuple4) #NameError: name 'tuple4' is not defined
63
64. Collection of data types
Sets in Python
A Set is an unordered collection data type that is iterable, mutable and
has no duplicate elements.
Python’s built-in set type has the following characteristics:
Sets are unordered.
Set elements are unique. Duplicate elements are not allowed.
A set itself may be modified, but the elements contained in the
set must be of an immutable type.
64
65. Collection of data types
Sets in Python
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.
This is based on a data structure known as a hash table. Since sets are
unordered, we cannot access items using indexes like we do in lists.
myset = set(["a", "b", "c"])
myset=set(("a", "b", "c”))
myset = {"a", "b", "c","a"}
65
66. Collection of data types
Sets in Python
An empty set is falsy in Boolean context:
x = set( )
print(bool(x)) # output will be False
The elements in a set can be objects of different types:
x = {42, 'foo', (1, 2, 3), 3.14159} # tuples are immutable
But lists and dictionaries are mutable, so they can’t be set elements:
x = {42, 'foo', [1, 2, 3], 3.14159} # ERROR UNHASHABLE TYPE ‘LIST’
66
67. Collection of data types
Sets in Python : Size and Membership
The len( ) function returns the number of elements in a set, and the in
and not in operators can be used to test for membership:
x = {42, 'foo', (1, 2, 3), 3.14159}
print(len(x)) # 4
if 42 in x:
print("42 is present in x")
if 'food' not in x:
print("food not present in x") 67
68. Collection of data types
Sets in Python : Operating on a Set
Many of the operations that can be used for Python’s other composite
data types don’t make sense for sets.
For example, sets can’t be indexed or sliced.
However, Python provides a whole host of operations on set objects that
generally mimic the operations that are defined for mathematical sets.
68
69. Collection of data types
Sets in Python : Operators vs. Methods
Most, though not quite all, set operations in Python can be performed in
two different ways: by operator or by method.
Given two sets, x1 and x2, the union of x1 and x2 is a set consisting of
all elements in either set.
x1={1,2,3,4,5}
x2={4,5,6,7,8,9,10}
print(x1.union(x2))
print(x1|x2)
Difference between union and | operator
print(x1.union( (4,5,6,7,8,9,10) ) )
print(x1 | (4,5,6,7,8,9,10) ) # unsupported operand type(s) for |: 'set' and 'tuple'69
70. Collection of data types
Sets in Python : Operators vs. Methods
More than two sets may be specified with either the operator or the
method:
a = {1, 2, 3, 4}
b = {2, 3, 4, 5}
c = {3, 4, 5, 6}
d = {4, 5, 6, 7}
print("Using union method", a.union(b, c, d) )
print("Using | operator ", a | b | c | d)
Intersection: x1.intersection(x2) and x1 & x2 return the set of elements
common to both x1 and x2:
print("Using intersection method",a.intersection(b, c, d))
print("Using & operator ",a & b & c & d)
70
71. Collection of data types
Sets in Python : Operators vs. Methods
difference: x1.difference(x2) and x1 - x2 return the set of all elements
that are in x1 but not in x2:
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}
print("Demo of difference in set ", x1.difference(x2)) # output ‘bar’,’foo’
71
72. Collection of data types
Sets in Python : Operators vs. Methods
difference: x1.difference(x2) and x1 - x2 return the set of all elements
that are in x1 but not in x2:
a = {1, 2, 3, 30, 300}
b = {10, 20, 30, 40}
c = {100, 200, 300, 400}
print(a.difference(b, c)
Print(a-b-c)
72
73. Collection of data types
Sets in Python : Operators vs. Methods
a = {1, 2, 3, 30, 300}
b = {10, 20, 30, 40}
c = {100, 200, 300, 400}
print(a-b-c)
print(a.difference(b, c) # output 1,2,3
When multiple sets are specified, the operation is performed from left to right.
In the example above, a - b is computed first, resulting in {1, 2, 3, 300}. Then
c is subtracted from that set, leaving {1, 2, 3}: 73
74. Collection of data types
Sets in Python : Operators vs. Methods
symmetric_difference: x1.symmetric_difference(x2) and x1 ^ x2 return the set of
all elements in either x1 or x2, but not both:
The ^ operator also allows more than two sets
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}
print(x1.symmetric_difference(x2))
print(x1 ^ x2)
#Output ‘foo’, ‘bar’, ‘qux’, ‘quux’
a = {1, 2, 3, 4, 5}
b = {10, 2, 3, 4, 50}
#a^b 1,5,10,50
c = {1, 50, 100}
# ans^c 5, 10, 100
print(a ^ b ^ c)
print(a.symmetric_difference(b, c))
74
75. Collection of data types
Sets in Python : Operators vs. Methods
x1.isdisjoint(x2): x1.isdisjoint(x2) returns True if x1 and x2 have no
elements in common:
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}
x1.isdisjoint(x2) # ‘baz is common’
#Output False
Note: There is no operator that corresponds to the .isdisjoint()
method.
75
77. Collection of data types
Sets in Python : Operators vs. Methods
issubset( ): Determine whether one set is a subset of the other.
In set theory, a set x1 is considered a subset of another set x2 if every
element of x1 is in x2.
All PJC students are part of JNC students (PJC students are the subset of JNC
Students)
77
78. Collection of data types
Sets in Python : Operators vs. Methods
Definition: In set theory, a set x1 is considered a subset of another set x2
if every element of x1 is in x2.
x1.issubset(x2) and x1 <= x2 return True if x1 is a subset of x2:
x1={1,2,3}
x2={1,2,3,4,5}
print(x1.issubset(x2)) # output True
print(x1<=x2) # output True
A set is considered to be a subset of itself:
print(x1.issubset(x1)) # output True
78
79. Collection of data types
Sets in Python : Operators vs. Methods
Proper subset: x1 < x2 Determines whether one set is a proper subset of the
other.
A proper subset is the same as a subset, except that the sets can’t be
identical.
A set x1 is considered a proper subset of another set x2 if every element of x1
is in x2, and x1 and x2 are not equal.
x1={1,2,3}
x2={1,2,3,4,5}
print(x1 < x2) # output True
While a set is considered a subset of itself, it is not a proper subset of itself:
print(x1 < x1) # output False
Note: The < operator is the only way to test whether a set is a proper subset. There is no
corresponding method. 79
80. Collection of data types
Sets in Python : Operators vs. Methods
issuperset x1.issuperset(x2) or x1 >= x2 Determine whether one set is
a superset of the other.
A superset is the reverse of a subset. A set x1 is considered a superset
of another set x2 if x1 contains every element of x2.
x1.issuperset(x2) and x1 >= x2 return True if x1 is a superset of x2:
80
81. Collection of data types
Sets in Python : Operators vs. Methods
x1={1,2,3}
x2={1,2,3,4,5}
print(x1>=x2) # output False
print(x2 >= x1) # output True
We know that a set is considered a subset of itself. A set is also
considered a superset of itself:
print(x1 >= x1) # output True
81
82. Collection of data types
Sets in Python : Operators vs. Methods
Proper Superset: x1 > x2 Determines whether one set is a proper superset of
the other.
A proper superset is the same as a superset, except that the sets can’t be
identical.
A set x1 is considered a proper superset of another set x2 if x1 contains every
element of x2, and x1 and x2 are not equal.
x1 > x2 returns True if x1 is a proper superset of x2:
x1={1,2,3}
x2={1,2,3,4,5}
print(x1 > x2) # output False
print(x2 > x1) # output True
A set is not a proper superset of itself: 82
83. Collection of data types
Sets in Python : Modifying a Set
Although the elements contained in a set must be of immutable type,
sets themselves can be modified. Like the operations above, there are a
mix of operators and methods that can be used to change the contents of
a set.
Augmented Assignment Operators and Methods
Each of the union, intersection, difference, and symmetric difference
operators learned so far has an augmented assignment form that can be
used to modify a set. For each, there is a corresponding method as well.
83
84. Collection of data types
Sets in Python : Modifying a Set
Modify a set by union.
x1.update(x2[, x3 ...]) or x1 |= x2 [| x3 ...]:
x1.update(x2) and x1 |= x2 add to x1 any elements in x2 that x1 does
not already have:
x1={1,2,3,6}
x2={1,2,3,4,5}
x1 |= x2 or x1.update(x2)
print(x1) # output {1,2,3,4,5,6} 84
85. Collection of data types
Sets in Python : Modifying a Set
Modify a set by intersection.
x1.intersection_update(x2[, x3 ...]) or x1 &= x2 [& x3 ...]:
x1.intersection_update(x2) and x1 &= x2 update x1, retaining only
elements found in both x1 and x2:
x1={1,2,3,6}
x2={1,2,3,4,5}
x1 &= x2 or x1.intersection_update(x2)
print(x1) # output {1,2,3} 85
86. Collection of data types
Sets in Python : Modifying a Set
Modify a set by difference.
x1.difference_update(x2[, x3 ...]) or x1 -= x2 [| x3 ...]
x1.difference_update(x2) and x1 -= x2 update x1, removing
elements found in x2:
x1={1,2,3,6}
x2={1,2,3,4,5}
x1-= x2 or x1.difference_update(x2)
print(x1) # output {6}
86
87. Collection of data types
Sets in Python : Modifying a Set
Modify a set by symmetric difference.
x1.symmetric_difference_update(x2) and x1 ^= x2 update
x1, retaining elements found in either x1 or x2, but not
both:
x1={1,2,3,6}
x2={1,2,3,4,5}
x1 ^= x2 or x1.symmetric_difference_update(x2)
print(x1) # output {4,5,6} 87
88. Collection of data types
Sets in Python : Other Methods For Modifying Sets
x.add(<elem>): Adds an element to a set.
x1={1,2,3,6}
x1.add(7)
print(x1) # output {1,2,3,6,7}
x.remove(<elem>): Removes an element from a set.
x1.remove(7)
print(x1) # output {1,2,3,6}
88
89. Collection of data types
Sets in Python : Other Methods For Modifying Sets
x.discard(<elem>): Removes an element from a set.
If <elem> is not in x, this method quietly does nothing instead
of raising an exception:
x1={1,2,3,6}
x1.add(7)
x1.remove(7)
x1.remove(7) # ERROR
x1.remove(8) # ERROR
x1.discard(6)
x1.discard(8)
print(x1) # output {1,2,3}
89
90. Collection of data types
Sets in Python : Other Methods For Modifying Sets
x.pop( ): Removes a random element from a set.
x.pop( ) removes and returns an arbitrarily chosen element
from x. If x is empty, x.pop( ) raises an exception:
x1={1,2,3,6}
x1.pop( )
print(x1) # output 2,3,6
x.clear( ): Clears a set.
x1={1,2,3,6}
x1.clear( )
print(x1) # output set( )
90
91. Collection of data types
Frozen Sets in Python :
Python provides another built-in type called a frozenset,
which is in all respects exactly like a set, except that a
frozenset is immutable.
We can perform non-modifying operations on a frozenset:
fs1=frozenset([1,2,3,6])
fsx2=frozenset([1,2,3,4,5])
print(type(fs1))
print(fs1)
91
92. Collection of data types
Frozen Sets in Python :
fs1=frozenset([1,2,3,6])
fsx2=frozenset([1,2,3,4,5])
print(type(fs1))
print(fs1)
print(len(fs1)) # output will be 4
But methods that attempt to modify a frozenset fail:
print("Add operation on frozenset : ", fs1.add(10)) # ERROR
print("pop operation on frozenset : ", fs1.pop( )) # ERROR
print("clear operation on frozenset : ", fs1.clear( )) # ERROR92
93. Collection of data types
Frozensets and Augmented Assignment
fs1=frozenset([1,2,3,6])
print(id(fs1))
fs2={1,2,3,4,5}
fs1 &= fs2 or fs1=fs1&fs2
print(fs1) # output frozenset({1,2,3})
print(id(fs1))
93
94. Collection of data types
Assignment: Demonstrate the following using images
union
intersection
difference
symmetric_difference
× isdisjoint
× issubset
× update
× intersection_update
× difference_update
× symmetric_difference_update 94
95. Collection of data types – Mapping Types
A mapping type is one that supports the membership operator (in)
and the size function (len( )), and is iterable.
Mappings are collections of key–value items and provide methods
for accessing items and their keys and values.
When iterated, unordered mapping types provide their items in an
arbitrary order.
Python 3.0 provides two unordered mapping types, the built-in dict
type and the standard library’s collections.defaultdict type.
A new, ordered mapping type, collections.OrderedDict, was
introduced with Python 3.1; this is a dictionary that has the same
methods and properties (i.e., the same API) as the built-in dict, but
stores its items in insertion order.
95
96. Collection of data types – Mapping Types
Only hashable objects may be used as dictionary keys.
Dictionary keys: float, frozenset, int, str, and tuple.
(Immutable data types)
Mutable types such as dict, list, and set cannot be used as
dictionary keys.
Key’s associated value can be an object reference referring to
an object of any type, including numbers, strings, lists, sets,
dictionaries, functions, and so on.
96
97. Collection of data types – Mapping Types
Dictionaries
A dict is an unordered collection of zero or more key–value
pairs whose keys are object references that refer to hashable
objects, and whose values are object references referring to
objects of any type.
Dictionaries are mutable, so we can easily add or remove
items, but since they are unordered they have no notion of
index position and so cannot be sliced or strided.
97
98. Collection of data types – Mapping Types
Defining a Dictionary
Dictionaries are Python’s implementation of a data structure
that is more generally known as an associative array. A
dictionary consists of a collection of key-value pairs.
Each key-value pair maps the key to its associated value.
We can define a dictionary by enclosing a comma-separated list
of key-value pairs in curly braces ({ }).
A colon (:) separates each key from its associated value:
98
99. Collection of data types – Mapping Types
Defining a Dictionary
myDictionary = {
<key>: <value>,
<key>: <value>,
<key>: <value>
} 99
100. Collection of data types – Mapping Types
Defining a Dictionary
We can also construct a dictionary with the built-in dict( ) function. The
argument to dict( ) should be a sequence of key-value pairs. A list of
tuples works well for this:
myDictionary = dict( [
(<key>, <value>),
(<key>, <value),
.
.
.
(<key>, <value>)
] )
100
101. Collection of data types – Mapping Types
Accessing Dictionary Values
You don’t get them by index, then how do you get them?
A value is retrieved from a dictionary by specifying its
corresponding key in square brackets ([ ]):
myDictionary[‘existing_key’]
If you refer to a key that is not in the dictionary, Python raises
an exception:
myDictionary[‘non_existing_key’] #ERROR
101
102. Collection of data types – Mapping Types
Accessing Dictionary Values
Adding an entry to an existing dictionary is simply a matter of
assigning a new key and value:
myDictionary[‘new_key’]=‘value’
If you want to update an entry, you can just assign a new
value to an existing key:
myDictionary[‘existing_key’]=‘new_value’
To delete an entry, use the del statement, specifying the key to
delete:
del myDictionary[‘existing_key’] 102
104. Collection of data types – Iterating and Copying
Collections
Once we have collections of data items, it is natural to
want to iterate over all the items they contain.
In this section’s first subsection we will introduce some of
Python’s iterators and the operators and functions that
involve iterators.
Another common requirement is to copy a collection.
There are some subtleties involved here because of
Python’s use of object references (for the sake of
efficiency), so in this section’s second subsection, we will
examine how to copy collections and get the behavior we
want.
104
105. Collection of data types – Iterating and Copying
Collections
Iterators and Iterable Operations and Functions
An iterable data type is one that can return each of its items one
at a time.
Any object that has an __iter__( ) method, or any sequence (i.e.,
an object that has a __getitem__( ) method taking integer
arguments starting from 0) is an iterable and can provide an
iterator.
An iterator is an object that provides a __next__( ) method
which returns each successive item in turn, and raises a
StopIteration exception when there are no more items.105
107. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
In Python, we use = operator to create a copy of an object. You
may think that this creates a new object; it doesn't. It only
creates a new variable that shares the reference of the original
object.
Let's take an example where we create a list named old_list and
pass an object reference to new_list using = operator.
107
108. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 'a']]
new_list = old_list
new_list[2][2] = 9
print('Old List:', old_list)
print('ID of Old List:', id(old_list))
print('New List:', new_list)
print('ID of New List:', id(new_list))
# ID of both Old list and New list is same108
109. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
Essentially, sometimes you may want to have the original values
unchanged and only modify the new values or vice versa. In
Python, there are two ways to create copies:
1. Shallow Copy
2. Deep Copy
To make these copy work, we use the copy module.
109
110. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
Copy Module: We use the copy module of Python for shallow
and deep copy operations. Suppose, you need to copy the
compound list say x. For example:
import copy
copy.copy(x) # Shallow copy
copy.deepcopy(x) #Deep copy
Here, the copy( ) return a shallow copy of x. Similarly,
deepcopy( ) return a deep copy of x.
110
111. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
Shallow Copy
A shallow copy creates a new object which stores the reference
of the original elements.
So, a shallow copy doesn't create a copy of nested objects,
instead it just copies the reference of nested objects. This
means, a copy process does not recurse or create copies of
nested objects itself.
111
112. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
Shallow Copy
import copy
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)
#old_list.append([4, 4, 4])
#old_list[1][1] = 'AA'
print("Old list:", old_list)
print("New list:", new_list) 112
113. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
Deep Copy
A deep copy creates a new object and recursively adds the
copies of nested objects present in the original elements.
Let’s continue with example 2. However, we are going to create
deep copy using deepcopy( ) function present in copy module.
The deep copy creates independent copy of original object and
all its nested objects.
113
114. Collection of data types – Iterating and Copying
Collections
Copy an Object in Python
Deep Copy
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'BB‘ # only old_list will be updated
print("Old list:", old_list)
print("New list:", new_list)
114