UNIT 2 Study Materials & Sample Programs
UNIT 2 Study Materials & Sample Programs
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary
can be of any data type and can be duplicated, whereas keys can’t be repeated and must be
immutable.
The data is stored in key:value pairs in dictionaries, which makes it easier to find values.
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by a ‘comma’.
print(d2)
print(d3)
Dictionary keys are case sensitive: the same name but different cases of Key will be treated
distinctly.
Keys must be immutable: This means keys can be strings, numbers, or tuples but not lists.
Keys must be unique: Duplicate keys are not allowed and any duplicate key will overwrite
the previous value.
Dictionary internally uses Hashing. Hence, operations like search, insert, delete can be
performed in Constant Time.
# example
d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }
del d2[“2"]
print(d2)
print(d2)
val = d1.pop(4)
print(val)
# Example Using popitem to removes and returns the last key-value pair.
print(d) # output {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all
types of items (including another list) in a list. A list may contain mixed type of items, this is possible
because a list mainly stores references at contiguous locations and actual items may be stored at
different locations. List can contain duplicate items. List in Python are Mutable. Hence, we can
modify, replace or delete the items. Lists are ordered. It maintains the order of elements based on
how they are added. Accessing items in List can be done directly using their position (index), starting
from 0.
# example
print(a)
Creating a List
a = [1, 2, 3, 4, 5]
# List of strings
print(a)
print(b)
print(c)
We can also create a list by passing an iterable (like a string, tuple, or another list) to list() function.
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)
We can create a list with repeated elements using the multiplication operator.
a = [2] * 5
b = [0] * 7
print(a)
print(b)
Elements in a list can be accessed using indexing. Python indexes start at 0, so a[0] will access the
first element, while negative indexing allows us to access elements from the end of the list. Like
index -1 represents the last elements of list.
print(a[0]) # ouput is 10
print(a[-1]) # output is 50
a = []
a.append(10)
print("After append(10):", a)
# Inserting 5 at index 0
a.insert(0, 5)
# Output -After extend([15, 20, 25]): [5, 10, 15, 20, 25]
a[1] = 25
print(a)
a.remove(30)
print("After remove(30):", a)
popped_val = a.pop(1)
del a[0]
We can iterate the Lists easily by using a for loop or other iteration methods. Iterating over lists is
useful when we want to do some operation on each item or access specific items based on certain
conditions. Let’s take an example to iterate over the list using for loop.
for item in a:
print(item)
Output
apple
banana
cherry
A nested list is a list within another list, which is useful for representing matrices or tables. We can
access nested elements by chaining indexes.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
Output
6
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This
includes letters, numbers, and symbols. Python has no character data type so single
character is a string of length 1.
Creating a String-
Strings can be created using either single (‘) or double (“) quotes.
s1 = ‘ABC'
s2 = “XYZ"
print(s1)
print(s2)
Multi-line Strings-
If we need a string to span multiple lines then we can use triple quotes (”’ or “””).
at Hindustan"""
print(s)
# output
# I am in second
# year at Hindustan
s = “LITERATURE"
print(s[0]) #ouput=L
print(s[4]) #output=R
Note: Accessing an index out of range will cause an IndexError. Only integers are allowed as
indices and using a float or other types will result in a TypeError.
Python allows negative address references to access characters from back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
# sample program
s = “LITERATURE"
print(s[-10])
print(s[-5])
String Slicing
Slicing is a way to extract portion of a string by specifying the start and end indexes.
The syntax for slicing is string[start:end], where start starting index and end is stopping
index (excluded).
s = “ALLTHEBEST"
print(s[1:4])
print(s[:3])
print(s[3:])
# Reverse a string
print(s[::-1])
#output is ‘TSEBEHTLLA’
String Immutability
Strings in Python are immutable. This means that they cannot be changed after they are
created. If we need to manipulate strings then we can use methods like concatenation,
slicing, or formatting to create new strings based on the original.
s = “LOVEINDIA"
s = “I" + s[0:]
print(s)
#output is ‘ILOVEINDIA’
Deleting a String
In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.
# example
s = "GfG"
Note: After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.
Updating a String
To update a part of a string we need to create a new string since strings are immutable.
# example
s = "hello Alice“
S1 = "H" + s[1:]
print(s1)
# replace “Alice" with “Varun"
print(s2)
Common String Methods- Python provides a various built-in methods to manipulate strings.
len(): The len() function returns the total number of characters in a string.
s = “Computer"
print(len(s))
# output: 8
s = "Hello World"
print(s.strip())
s = "Python is fun"
print(s.replace("fun", "awesome"))
We can concatenate strings using + operator and repeat them using * operator.
Strings can be combined by using + operator.
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)
s = "Hello "
print(s * 3)
Formatting Strings
Using f-strings
The simplest and most preferred way to format strings is by using f-strings.
name = "Alice"
age = 22
Using format()
# example program
print(s1)
Using in for String Membership Testing
s = “ANECDOTE"
Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in
terms of indexing, nested objects, and repetition but the main difference between both is Python
tuple is immutable, unlike the Python list which is mutable.
Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.
Like Lists, tuples are ordered and we can access their elements using their index values
t = (1, 2, 3, 4, 5)
print(t[1]) # 2
print(t[4]) # 5
t = (1, 2, 3, 4, 2, 3)
print(t) # (1, 2, 3, 4, 2, 3)
# updating an element
t[1] = 100
Tuples in Python provide two ways by which we can access the elements of a tuple.
t = (10, 5, 20)
Output
Value in t[0] = 10
Value in t[1] = 5
Value in t[2] = 20
In the above methods, we use the positive index to access the value in Python, and here we will use
the negative index within [].
t = (10, 5, 20)
Output
Value in t[-1] = 20
Value in t[-2] = 5
Value in t[-3] = 10
Like List Traversal, we can traverse through a tuple using for loop.
# Define a tuple
t = (1, 2, 3, 4, 5)
for x in t:
print(x, end=" ")
Output
12345
t1 = (0, 1, 2, 3)
t2 = ('hai', 'welcome')
print(t1 + t2)
Output
t1 = (0, 1, 2, 3)
t2 = ('hai', 'welcome')
t3 = (t1, t2)
print(t3)
Output
We can create a tuple of multiple same elements from a single element in that tuple.
t = ('python',)*3
print(t)
Output
('python', 'python', 'python')
Slicing a Python tuple means dividing a tuple into small tuples using the indexing method. In this
example, we slice the tuple from index 1 to the last element. In the second print statement, we
printed the tuple using reverse indexing. And in the third print statement, we printed the elements
from index 2 to 4.
t = (0 ,1, 2, 3)
print(t[1:])
print(t[::-1])
print(t[2:4])
Output
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error
because after deleting the tuple, it will give a Name Error.
Note: Remove individual tuple elements are not possible, but we can delete the whole Tuple using
Del keyword.
t = ( 0, 1)
del t
To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.
t = ('python', 'geek')
print(len(t)) # 2
Multiple Data Types With Tuple
Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple
datatypes.
print(t)
We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its
parameters.
a = [0, 1, 2]
t = tuple(a)
print(t)
Output: (0, 1, 2)
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are
taken as elements), and converts them to a tuple
Tuples in a Loop
t = ('gfg',)
n=5
for i in range(int(n)):
t = (t,)
print(t)
Output
(('gfg',),)
((('gfg',),),)
(((('gfg',),),),)
((((('gfg',),),),),)
(((((('gfg',),),),),),)
t = ("gfg", "Python")
print(t)
Without Brackets
t = 4, 5, 6
Tuple Constructor
t = tuple([7, 8, 9])
Empty Tuple
t = ()
print(t) # Output: ()
print(type(t))
print(t)
print(type(t))
Using Tuple Packing
# Tuple packing
a, b, c = 11, 12, 13
t = (a, b, c)
Python set is an unordered collection of multiple items having different datatypes. In Python, sets
are mutable, unindexed and do not contain duplicates. The order of elements in a set is not
preserved and can change.
In Python, the most basic and efficient method for creating a set is using curly braces.
set1 = {1, 2, 3, 4}
print(set1) # {1, 2, 3, 4}
Python Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by a ‘comma’.
Note: A Python set cannot have mutable elements like a list or dictionary, as it is immutable.
# Creating a Set
set1 = set()
print(set1)
set1 = set("ALLTHEBEST")
print(set1)
print(set1)
print(set(tup))
In set, the order of elements is not guaranteed to be the same as the order in which they were
added. The output could vary each time we run the program. Also the duplicate items entered are
removed by itself.
Sets do not support indexing. Trying to access an element by index (set[0]) raises a TypeError.
We can add elements to the set using add(). We can remove elements from the set using remove ().
The set changes after these operations, demonstrating its mutability. However, we cannot change its
items directly.
We can add items to a set using add() method and update() method.
# Creating a set
set1 = {1, 2, 3}
set1.add(4)
set1.update([5, 6])
print(set1)
Output
{1, 2, 3, 4, 5, 6}
We can loop through a set to access set items as set is unindexed and do not support accessing
elements by indexing. Also we can use in keyword which is membership operator to check if an item
exists in a set.
for i in set1:
# using in keyword
We can remove an element from a set in Python using several methods: remove(), discard() and
pop(). Each method works slightly differently :
remove() method removes a specified element from the set. If the element is not present in the set,
it raises a KeyError. discard() method also removes a specified element from the set. Unlike
remove(), if the element is not found, it does not raise an error.
set1 = {1, 2, 3, 4, 5}
set1.remove(3)
print(set1) # {1, 2, 4, 5}
try:
set1.remove(10)
except KeyError as e:
print("Error:", e) # Error: 10
set1.discard(4)
print(set1) # {1, 2, 5}
print(set1) # {1, 2, 5}
Note: If the set is unordered then there’s no such way to determine which element is popped by
using the pop() function.
set1 = {1, 2, 3, 4, 5}
val = set1.pop()
print(val) # 1
print(set1) # {2, 3, 4, 5}
clear() method removes all elements from the set, leaving it empty.
set1 = {1, 2, 3, 4, 5}
set1.clear()
print(set1) # set()
A frozenset in Python is a built-in data type that is similar to a set but with one key difference that is
immutability. This means that once a frozenset is created, we cannot modify its elements that is we
cannot add, remove or change any items in it. Like regular sets, a frozenset cannot contain duplicate
elements.
set1 = {3, 1, 4, 1, 5}
fset = frozenset(set1)
li = [1, 2, 3, 3, 4, 5, 5, 6, 2]
set1 = set(li)
print(set1)
s = "AllTheBest"
set1 = set(s)
print(set1)
set1 = set(d)
print(set1)
Unique Elements: Sets can only contain unique elements, so they can be useful for removing
duplicates from a collection of data.
Fast Membership Testing: Sets are optimized for fast membership testing, so they can be
useful for determining whether a value is in a collection or not.
Mathematical Set Operations: Sets support mathematical set operations like union,
intersection and difference, which can be useful for working with sets of data.
Mutable: Sets are mutable, which means that you can add or remove elements from a set
after it has been created.
Unordered: Sets are unordered, which means that you cannot rely on the order of the data
in the set. This can make it difficult to access or process data in a specific order.
Limited Functionality: Sets have limited functionality compared to lists, as they do not
support methods like append() or pop(). This can make it more difficult to modify or
manipulate data stored in a set.
Memory Usage: Sets can consume more memory than lists, especially for small datasets.
This is because each element in a set requires additional memory to store a hash value.
Less Commonly Used: Sets are less commonly used than lists and dictionaries in Python,
which means that there may be fewer resources or libraries available for working with them.
This can make it more difficult to find solutions to problems or to get help with debugging.
Overall, sets can be a useful data structure in Python, especially for removing duplicates or for fast
membership testing. However, their lack of ordering and limited functionality can also make them
less versatile than lists or dictionaries, so it is important to carefully consider the advantages and
disadvantages of using sets when deciding which data structure to use in your Python program.
Python Lists Tuples in Python Python Sets
In Python, a list is a built-in Python Tuple is a collection Python set is an unordered
dynamic sized array of objects separated by collection of multiple items
(automatically grows and commas. A tuple is similar to having different datatypes.
shrinks). A list may contain a Python list in terms of In Python, sets are mutable,
mixed type of items, List can indexing, nested objects, and unindexed and do not
contain duplicate items. List repetition but the main contain duplicates. The order
in Python are Mutable. difference between both is of elements in a set is not
Hence, we can modify, Python tuple is immutable preserved and can change.
replace or delete the items. t = (10, 20, 30)
Lists are ordered. It
maintains the order of
elements based on how they
are added. Accessing items
in List can be done directly
using their position (index),
starting from 0.
Using Square Brackets Unlike Python lists, tuples Creating a Set in Python
# List of integers are immutable. Like Lists, In Python, the most basic
a = [1, 2, 3, 4, 5] tuples are ordered and we and efficient method for
# List of strings can access their elements creating a set is using curly
b = ['apple', 'banana', using their index values braces.
'cherry'] We cannot update items to a set1 = {1, 2, 3, 4}
# Mixed data types tuple once it is created.
c = [1, 'hello', 3.14, True] Tuples cannot be appended
or extended.
We cannot remove items
from a tuple once it is
created.
Using list() Constructor Adding Elements to a Set in
a = list((1, 2, 3, 'apple', 4.5)) Python
Accessing List Elements Accessing Values # Creating a set
# Access first element print("Value in t[0] = ", t[0]) set1 = {1, 2, 3}
print(a[0 print("Value in t[1] = ", t[1]) # Add one item
# Access last element print("Value in t[-1] = ", t[-1]) set1.add(4)
print(a[-1]) print("Value in t[-2] = ", t[-2]) # Add multiple items
set1.update([5, 6])
Adding Elements into List Concatenation of Python Accessing a Set in Python
•append(): Adds an element Tuples We can loop through a set to
at the end of the list. To Concatenation of Python access set items as set is
•extend(): Adds multiple Tuples, we will use plus unindexed and do not
elements to the end of the operators (+). support accessing elements
list. t1 = (0, 1, 2, 3) by indexing. Also we can use
•insert(): Adds an element at t2 = ('hai', 'welcome') in keyword which is
a specific position. print(t1 + t2) membership operator to
Output check if an item exists in a
(0, 1, 2, 3, 'hai', 'welcome') set.
Removing Elements from List Nesting of Python Tuples set1 = set(["welcome", "to ",
•remove(): Removes the first t1 = (0, 1, 2, 3) "hindustan."])
occurrence of an element. t2 = ('hai', 'welcome') # Accessing element using
•pop(): Removes the t3 = (t1, t2) For loop
element at a specific index or print(t3) for i in set1:
the last element if no index Output print(i, end=" ") # welcome
is specified. ((0, 1, 2, 3), ('hai', to Hindustan.
•del statement: Deletes an 'welcome')) # Checking the element
element at a specified index. # using in keyword
print("to" in set1) # True
Slicing Tuples in Python Removing Elements from the
print(t[1:]) Set in Python
print(t[::-1]) Using remove() Method or
print(t[2:4]) discard() Method
Using pop() Method
Using clear() Method
Deleting a Tuple in Python
del t
Finding the Length of a
Python Tuple
print(len(t))
Assignment Operators in Python
The Python Operators are used to perform operations on values and variables. These are the special
symbols that carry out arithmetic, logical, and bitwise computations. The value the operator
operates on is known as the Operand.
Assignment Operators are used to assign values to variables. This operator is used to assign the
value of the right side of the expression to the left side operand.
a=3
b=5
c=a+b
print(c)
The Addition Assignment Operator is used to add the right-hand side operand with the left-hand
side operand and then assigning the result to the left operand.
a=3
b=5
#a=a+b
a += b
print(a)
The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-
hand side operand and then assigning the result to the left-hand side operand.
a=3
b=5
#a=a-b
a -= b
print(a)
The Multiplication Assignment Operator is used to multiply the right-hand side operand with the
left-hand side operand and then assigning the result to the left-hand side operand.
a=3
b=5
#a=a*b
a *= b
print(a)
The Division Assignment Operator is used to divide the left-hand side operand with the right-hand
side operand and then assigning the result to the left operand.
a=3
b=5
#a=a/b
a /= b
print(a)
The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands
and then takes the remainder and assigns it to the left operand.
a=3
b=5
#a=a%b
a %= b
print(a)
The Floor Division Assignment Operator is used to divide the left operand with the right operand and
then assigns the result (floor value) to the left operand.
a=3
b=5
# a = a // b
a //= b
print(a)
Exponentiation Assignment Operator
The Exponentiation Assignment Operator is used to calculate the exponent (raise power) value using
operands and then assigning the result to the left operand.
a=3
b=5
# a = a ** b
a **= b
print(a)
The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands
and then assigning the result to the left operand.
a=3
b=5
#a=a&b
a &= b
# Output
print(a)
The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and
then assigning result to the left operand.
a=3
b=5
#a=a|b
a |= b
# Output
print(a)
The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands
and then assigning result to the left operand.
a=3
b=5
#a=a^b
a ^= b
# Output
print(a)
The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the
operands and then assign result to the left operand.
a=3
b=5
# a = a >> b
a >>= b
# Output
print(a)
The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the
operands and then assign result to the left operand.
a=3
b=5
# a = a << b
a <<= b
# Output
print(a)
Python Bitwise Operators
Python bitwise operators are used to perform bitwise calculations on integers. The integers are first
converted into binary and then operations are performed on each bit or corresponding pair of bits,
hence the name bitwise operators. The result is then returned in decimal format.
Python Bitwise AND (&) operator takes two equal-length bit patterns as parameters. The two-bit
integers are compared. If the bits in the compared positions of the bit patterns are 1, then the
resulting bit is 1. If not, it is 0.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of
both X & y
a = 10
b=4
Bitwise OR Operator
The Python Bitwise OR (|) Operator takes two equivalent length bit designs as boundaries; if the two
bits in the looked-at position are 0, the next bit is zero. If not, it is 1.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of
both X, Y
a = 10
b=4
print("a | b =", a | b)
The Python Bitwise XOR (^) Operator also known as the exclusive OR operator, is used to perform
the XOR operation on two operands. XOR stands for “exclusive or”, and it returns true if and only if
exactly one of the operands is true. In the context of bitwise operations, it compares corresponding
bits of two operands. If the bits are different, it returns 1; otherwise, it returns 0.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of
both X & Y
a = 10
b=4
print("a ^ b =", a ^ b)
The preceding three bitwise operators are binary operators, necessitating two operands to function.
However, unlike the others, this operator operates with only one operand.
Python Bitwise Not (~) Operator works with a single value and returns its one’s complement. This
means it toggles all bits in the value, transforming 0 bits to 1 and 1 bits to 0, resulting in the one’s
complement of the binary number.
Example: Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.
a = 10
b=4
Bitwise Shift
These operators are used to shift the bits of a number left or right thereby multiplying or dividing
the number by two respectively. They can be used when we have to multiply or divide a number by
two.
Shifts the bits of the number to the right and fills 0 on voids left (fills 1 in the case of a negative
number) as a result. Similar effect as of dividing the number with some power of two.
Example 1:
Example 2:
a = 10
b = -10
Operator Overloading means giving extended meaning beyond their predefined operational
meaning. For example operator + is used to add two integers as well as join two strings and merge
two lists. It is achievable because the ‘+’ operator is overloaded by int class and str class. You might
have noticed that the same built-in operator or function shows different behavior for objects of
different classes, this is called Operator Overloading.
Performing arithmetic operations in a more optimized way when dealing with low-level
programming, such as manipulating hardware registers or implementing cryptographic algorithms.
Bitwise operators work at the binary level, which is the lowest level of data representation in
computers.
They are typically used in scenarios where fine-grained control over individual bits is necessary, such
as low-level programming, cryptography, and hardware interfacing.
Understanding bitwise operations is crucial for writing efficient code and implementing certain
algorithms.
# Bitwise OR (|)
result_or = num1 | num2
print("Bitwise OR:", result_or)
result_not2 = ~num2
print("Bitwise NOT (num2):", result_not2)
s = “All is Well!“
# Count the characters using len() function
count = len(s)
print(count)
Lab Practice Program -21
Python program to count the number of spaces
in string