Python Notes - 2 Unit_240513_171101
Python Notes - 2 Unit_240513_171101
A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements, loops, and function
calls.
Sequential
Sequential statements are a set of statements whose execution process happens in a sequence.
The problem with sequential statements is that if the logic has broken in any one of the lines, then
the complete source code execution will break.
Example:
# This is a Sequential statement
a=600
b=200
c=a-b
print("Subtraction is : ",c)
In Python, the selection statements are also known as Decision control statements or branching
statements.
The selection statement allows a program to test several conditions and execute instructions based
on which condition is true.
Some decision control statements are:
if
if-else
nested if
if-elif-else
Example:
n = 10
if n % 2 == 0:
print("n is an even number")
3. Repetition
Example:
print("1st example")
lst = [1, 2, 3]
for i in range(len(lst)):
print(lst[i], end = " \n")
print("2nd example")
for j in range(0,5):
print(j, end = " \n")
1. Conditionally executing code: The if-else statement is used to execute specific code
based on a condition. This allows us to selectively execute certain parts of the code based
on the input data or the state of the program.
2. Repeating code: Loops such as for loop and while loop are used to execute a block of
code repeatedly based on a condition. This is useful when we want to perform a specific
operation multiple times, such as processing a list of items or iterating over a range of
numbers.
3. Exiting loops: The break statement is used to exit a loop prematurely when a specific
condition is met. This is useful when we want to terminate a loop when we have found
the desired value or have encountered an error condition.
4. Skipping iterations: The continue statement is used to skip a specific iteration of a loop
when a particular condition is met. This is useful when we want to exclude specific
values from the loop, such as even numbers or duplicates.
5. Handling errors: The try-except statement is used to handle errors that may occur
during the execution of a program. This allows us to gracefully handle errors and prevent
the program from crashing.
Basic if Statement
In Python, if statements are a starting point to implement a condition. Let’s look at the simplest
example:
if <condition>:
<expression>
When <condition> is evaluated by Python, it’ll become either True or False (Booleans). Thus, if
the condition is True (i.e, it is met), the <expression> will be executed, but if <condition> is
False (i.e., it is not met), the <expression> won’t be executed.
Example:
# Basic if statement
x=3
y = 10
if x < y:
print("x is smaller than y.")
else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But if we want to do something else if the condition is false, we can use the else
statement with the if statement Python to execute a block of code when the Python if condition is false.
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example:
# else statement
x=3
y = 10
if x > y:
print("x is greater than y.")
else:
print("x is smaller than y.")
elif Statement
In python, elif keyword is a short form of else-if and it useful to define multiple conditional expressions
between if and else statements. The elif keyword is pythons’ way of saying "if the previous conditions were
not true, then try this condition".
The elif keyword will combine both if and else statements and create if-elif-else statements.
The if-elif-else statements will contain multiple conditional expressions, but only one boolean
expression evaluates to True and execute the respective block of statements.
if boolean_expression1:
statement(s)
elif boolean_expression2:
statement(s)
elif boolean_expression3:
statement(s)
else:
statement(s)
If you observe the above if elif else statement syntax, the statements inside of if condition will
execute only when the boolean_expression returns True otherwise, it will validate the next condition
of elif block, and so on. In case if all the defined expressions are False, the else block statements
will be executed.
Example:
x = 30
y = 50
if x > y:
print("x is greater than y")
elif y > x:
print ("y is greater than x")
else:
print("x and y are equal")
Nested if Statement
if statement can also be checked inside other if statement. This conditional statement is called a nested if
statement. This means that inner if condition will be checked only if outer if condition is true and by this,
we can see multiple conditions to be satisfied.
Example:
# Nested if statement example
num = 10
if num > 5:
print("Bigger than 5")
if num <= 15:
print("Between 5 and 15")
If you create if-else statements inside other if-else statements, we will call them nested if-else statements
in python. The nested if-else statements are useful when you want to execute the block of code/statements
inside other if-else statements.
if boolean_expression:
if boolean_expression:
statement(s)
else:
statement(s)
else:
Dr. Yusuf Perwej Page 5
statement(s)
If you observe the above nested if-else statement syntax, we created an if-else statement inside another if-
else statement.
Example:
x = 30
y = 10
if x >= y:
print("x is greater than or equals to y")
if x == y:
print("x is equals to y")
else:
print("x is greater than y")
else:
print("x is less than y")
Loops
Python offers 3 choices for running the loops. The basic functionality of all the techniques is the
same, although the syntax and the amount of time required for checking the condition differ. We
can run a single statement or set of statements repeatedly using a loop command. The following
sorts of loops are available in the Python programming language.
Name of the
Sr.No. Loop Type & Description
loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the
1 While loop
condition before executing the loop body.
This type of loop executes a code block multiple times and abbreviates the code that
2 For loop
manages the loop variable.
3 Nested loops We can iterate a loop inside another loop.
The for loop in Python is an iterating function. A for loop is a general, flexible method of
iterating through an iterable object. Any object that can return one member of its group at a time
is an iterable in Python. The basic syntax of the for loop in Python.
The first word of the statement starts with the keyword “for” which signifies the beginning of
the for loop.
Then we have the iterator variable which iterates over the sequence and can be used within the
loop to perform various functions
The next is the “in” keyword in Python which tells the iterator variable to loop for elements
within the sequence
And finally, we have the sequence variable which can either be a list, a tuple, or any other kind
of iterator.
The statements part of the loop is where you can play around with the iterator variable and
perform various function.
Example:
for num in range(1,11):
print(num)
Example:
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
print(num)
Example:
nums = (1, 2, 3, 4)
sum_nums = 0
for num in nums:
sum_nums = sum_nums + num
print(f'Sum of numbers is {sum_nums}')
Output
Sum of numbers is 10
Dr. Yusuf Perwej Page 7
Nested for Loops
When we have a for loop inside another for loop, it’s called a nested for loop. There are multiple
applications of a nested for loop.
This is where a nested for loop works better. The first loop (parent loop) will go over the words
one by one. The second loop (child loop) will loop over the characters of each of the words.
Example:
months = ["jan", "feb", "mar"]
days = ["sun", "mon", "tue"]
for x in months:
for y in days:
print (x, y)
Output
jan sun
jan mon
jan tue
feb sun
feb mon
feb tue
mar sun
mar mon
mar tue
Example:
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
Output
14
15
24
25
Example:
# Running outer loop from 2 to 3
for i in range(2, 4):
# Printing inside the outer loop
# Running inner loop from 1 to 10
for j in range(1, 11):
# Printing inside the inner loop
print(i, "*", j, "=", i*j)
# Printing inside the outer loop
print()
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
While Loop
In Python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately after the loop
in the program is executed.
while condition:
# body of while loop
Example:
number = 1
while number <= 3:
print(number)
number = number + 1
Dr. Yusuf Perwej Page 9
Example:
# In Python for Printing those numbers divisible by either 5 or 7 within 1 to 50 using a while loop.
i=1
while i<51:
if i%5 == 0 or i%7==0 :
print(i, end=' ')
i+=1 It asks the user to enter a number.
Output
5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50
To create a nested loop in Python, we can simply place a loop structure inside of the block of
statements that is repeated by another loop structure.
while expression:
while expression:
statement(s)
statement(s)
Example:
x = [1, 2]
y = [4, 5]
i=0
while i < len(x) :
j=0
while j < len(y) :
print(x[i] , y[j])
j=j+1
i=i+1
If the condition of a while loop is always True, the loop runs for infinite times, forming an infinite
while loop.
Example:
age = 32
# the test condition is always True
while age > 18:
print('You can vote')
or
The above program is equivalent to:
Example:
age = 32
# the test condition is always True
while True:
print('You can vote')
Loop Manipulation
Loop control statements change execution from their normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.
break Statement
The break statement is used to exit the for loop prematurely. It is used when we want to exit the
loop before it has completed all of its iterations.
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
if fruit == 'banana':
break
print(fruit)
Output:
apple
Explanation:
In this above code, the for loop iterates over each element in the “fruits” list and prints it on a
new line. However, when the “fruit” variable equals “banana”, the break statement is executed,
and the loop is terminated.
Example:
for i in range(5):
if i == 3:
break
print(i)
continue Statement
The continue statement skips the current iteration of the loop and it is used when we want to skip
a certain element in the sequence and continue with the next iteration of the loop.
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
if fruit == 'banana':
continue
print(fruit)
Output
apple
cherry
Explanation:
In this example, the for loop iterates over each element in the “fruits” list and prints it on a new
line. However, when the “fruit” variable is equal to “banana”, the continue statement is
executed, and the current iteration of the loop is skipped.
Example:
for i in range(5):
if i == 3:
continue
print(i)
Example:
# Python program to show how the continue statement works
# Initiating the loop
for string in "Python Gitms":
if string == "o" or string == "i" or string == "t":
continue
print('Current Letter:', string)
Output
Current Letter: P
Dr. Yusuf Perwej Page 12
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: G
Current Letter: m
Current Letter: s
pass Statement
In Python programming, the pass statement is a null statement which can be used as a
placeholder for future code. In other words, it is used when we want to write empty code blocks
and want to come back and fill them in later.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it
in the future. In such cases, we can use the pass statement.
In this syntax, the variable is a temporary variable that holds the value of each element in the
sequence during each iteration of the loop.
The pass statement is used to create an empty code block, which is filled later.
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
# Code block to be filled later
pass
Explanation:
In this example, the for loop iterates over each element in the “fruits” list, and an empty code
block is created using the pass statement.
Example:
n = 10
# use pass inside if statement
if n > 10:
pass
print('Hello')
Output
Hello
Example:
x = 10
if x > 5:
pass
else:
print ("x is less than or equal to 5")
When we run this program, it will not output anything, as the pass statement does nothing.
However, it serves as a placeholder for the code that we will write in the future.
Note: The difference between a comment and a pass statement in Python is that while the
interpreter ignores a comment entirely, pass is not ignored.
else Statement
In other languages, the else functionality is only provided in if-else pairs. But Python allows us
to implement the else functionality with for loops as well.
The else functionality is available for use only when the loop terminates normally. In case of
forceful termination of the loop else statement is overlooked by the interpreter and hence its
execution is skipped.
NOTE: When the loop is not terminated by a break statement, the else block
immediately after for/while is executed.
Example:
for i in ['G','O']:
print(i)
else:
# Loop else statement
# there is no break statement in for loop, hence else part gets executed directly
print("ForLoop-else statement successfully executed")
Output
G
O
ForLoop-else statement successfully executed
Example:
def print_sum_even_nums(even_nums):
total = 0
for x in even_nums:
if x % 2 != 0:
break
Output
For loop executed normally
Sum of numbers 20
The following example illustrates the combination of an else statement with a for statement in
Python. Till the count is less than 5, the iteration count is printed. As it becomes 5, the print
statement in else block is executed, before the control is passed to the next statement in the main
program.
Python range is one of the built-in functions. When you want the for loop to run for a specific
number of times, or you need to specify a range of objects to print out, the range function works
really well. By default, the sequence starts at 0, increments by 1, and stops before the specified
number.
When working with range(), you can pass between 1 and 3 integer arguments to it:
start states the integer value at which the sequence begins, if this is not included then
start begins at 0
stop is always required and is the integer that is counted up to but not included
step sets how much to increase (or decrease in the case of negative numbers) the next
iteration, if this is omitted then step defaults to 1
Consider the following example where I want to print the numbers 0, 1, and 2:
Example:
for x in range(3):
print("Printing:", x)
Output
Printing: 0
Printing: 1
Printing: 2
Example:
# create a sequence from 0 to 3 (4 is not included)
numbers = range(4)
# iterating through the sequence
for i in numbers:
print(i)
Output
The range function also takes another parameter apart from the start and the stop. This is the step
parameter. It tells the range function how many numbers to skip between each count.
In the below example, I’ve used number 3 as the step and you can see the output numbers are the
previous number + 3.
Example:
for n in range(1, 10, 3):
print("Printing with step:", n)
Output
Printing with step: 1
Printing with step: 4
Printing with step: 7
range() Syntax
range(start, stop, step)
The start and step arguments are optional.
We can also use a negative value for our step argument to iterate backwards, but we’ll have to
adjust our start and stop arguments accordingly:
Example:
for i in range(100,0,-10):
print(i)
Here, 100 is the start value, 0 is the stop value, and -10 is the range, so the loop begins at 100
and ends at 0, decreasing by 10 with each iteration. This occurs in the output:
Output
100
90
80
70
60
50
40
30
20
10
Output
[2, 3, 4]
[-2, -1, 0, 1, 2, 3]
[]
Output
[2, 5, 8]
[4, 3, 2, 1, 0]
[0, 1, 2, 3, 4]
List
A list in Python is a sequence data type used for storing a comma-separated collection of objects
in a single variable. Lists are always ordered and can contain different types of objects (strings,
integers, Booleans, etc.). Since they are mutable data types, lists are a good choice for dynamic
data (that may be added or removed over time) and ordered collection of elements enclosed within
square brackets [].
The beauty of Python lists lies in their flexibility and convenience. Whether you're organizing
data, managing tasks, or solving complex problems, lists provide a powerful way to store and
manipulate information in your Python programs.
Syntax
Lists can either be defined with square brackets ([]) or with the built-in list() constructor method.
In any case, the values initially passed to the new list must be comma-separated.
To get the candy from a specific jar, you look at the label and pick the right one. Similarly, to get
an item from a list, you use its index. Here's how you do it in Python:
first_fruit = fruits[0]
print(first_fruit)
# Output: apple
second_fruit = fruits[1]
print(second_fruit)
# Output: banana
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
List items can be of any data type:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Python list() function takes any iterable as a parameter and returns a list. In Python iterable is
the object you can iterate over. A list object is a collection which is ordered and changeable.
Syntax: list(iterable)
Parameter:
Note: If we don’t pass any parameter then the list() function will return a list with zero elements
(empty list).
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Example
# initializing a set
set1 = {'A', 'B', 'C', 'D', 'E'}
# initializing a dictionary
dictionary = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
# printing
print(list1)
print(list2)
output
['D', 'A', 'B', 'C', 'E']
['A', 'B', 'C', 'D', 'E']
Note: In the case of dictionaries, the keys of the dictionary will be the items of the list. Also, the
order of the elements will be random.
Note: - set is unordered and un-indexed data structure. where as list is ordered data structure.
In this example, we are using list() function to take user input from the user and create a Python
list from that input.
Example:
# Taking input from user as list
# printing
Output
Please Enter List Elements: 12345
['1', '2', '3', '4', '5']
Unlike strings, lists are mutable. This means you can change their content after you create them.
S.no Method Description
Used for adding elements to the
1 append()
end of the List.
It returns a shallow copy of a
2 copy()
list
This method is used for
3 clear() removing all items from the
list.
These methods count the
4 count()
elements.
Adds each element of an
5 extend()
iterable to the end of the List
Returns the lowest index where
6 index()
the element appears.
Inserts a given element at a
7 insert()
given index in a list.
Removes and returns the last
8 pop() value from the List or the given
index value.
Removes a given object from
9 remove()
the List.
Reverses objects of the List in
10 reverse()
place.
Sort a List in ascending,
11 sort() descending, or user-defined
order
Calculates the minimum of all
12 min()
the elements of the List
Calculates the maximum of all
13 max()
the elements of the List
Example:
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)
Syntax:
list.insert(<position, element)
Note: The position mentioned should be within the range of List, as in this case between 0 and 4,
else wise would throw IndexError.
Example:
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2, 10087)
print(List)
Output
['Mathematics', 'chemistry', 10087, 1997, 2000]
Syntax: List1.extend(List2)
Example:
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
Output
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
Syntax: sum(List)
Example:
List = [1, 2, 3, 4, 5]
print(sum(List))
Dr. Yusuf Perwej Page 22
Output
15
The sum is calculated only for numeric values, else wise throws TypeError.
Example:
List = ['gfg', 'abc', 3]
print(sum(List))
Output:
Traceback (most recent call last):
File "", line 1, in
sum(List)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Syntax: List.count(element)
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output
4
Syntax: len(list_name)
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
Output
10
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
Output
1
Dr. Yusuf Perwej Page 23
Another example:
In this example, we are using index() method which is one of the list functions in Python,
searching the first occurrence of the element 2, starting from index 2 in the list.
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2, 2))
Output
4
Example:
numbers = [5, 2, 8, 1, 9]
print(min(numbers))
Output
1
Example:
numbers = [5, 2, 8, 1, 9]
print(max(numbers))
Output
9
Syntax: list.sort([key,[Reverse_flag]])
Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
Output
[5.33, 4.445, 3, 2.5, 2.3, 1.054]
Dr. Yusuf Perwej Page 24
11. Python reverse() Method
reverse() function reverses the order of list.
Example:
# creating a list
list = [1,2,3,4,5]
#reversing the list
list.reverse()
#printing the list
print(list)
Output
[5, 4, 3, 2, 1]
Example 1:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop())
Output
2.5
Example 2:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop(0))
Output
2.3
Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
del List[0]
print(List)
Output
[4.445, 3, 5.33, 1.054, 2.5]
Syntax: list.remove(element)
Example :
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)
print(List)
Output
[2.3, 4.445, 5.33, 1.054, 2.5]
Python lists can also be made to behave like stacks and queues.
Stacks follow a “last-in, first-out” insertion order. This behavior can be showcased with
the .append() and. pop() methods for adding to and removing from the top of the stack,
respectively:
Example :
stack_example = ["a", "b", "c"]
print(stack_example)
# Output: ['a', 'b', 'c']
stack_example.append(1)
stack_example.append(2)
stack_example.append(3)
print(stack_example)
# Output: ['a', 'b', 'c', 1, 2, 3]
stack_example.pop()
stack_example.pop()
print(stack_example)
# Output: ['a', 'b', 'c', 1]
Queues follow a “first-in, first-out” insertion order and also utilize the .append() and .pop()
methods:
Example :
queue_example = ["a", "b", "c"]
print(queue_example)
# Output: ['a', 'b', 'c']
queue_example.append(1)
queue_example.append(2)
print(queue_example)
# Output: ['a', 'b', 'c', 1, 2]
queue_example.pop(0)
print(queue_example)
# Output: ['b', 'c', 1, 2]
A dictionary is a data set of key-value pairs. It provides a way to map pieces of data to each
other and allows for quick access to values associated with keys.
In Python, dictionaries are dynamic and mutable, which means they can change.
Note: As of Python version 3.7, dictionaries are ordered based on insertion, but this is not the
case in previous versions.
Syntax
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by a ‘comma’.
The dictionary holds pairs of values, one being the Key and the other corresponding pair element
being its Key:value.
Dictionary keys must be immutable types such as numbers and strings because keys should not
change. Keys cannot be lists because lists are mutable, and it will raise a TypeError. Values in a
dictionary can be of any data type and can be duplicated.
Values can be any type, such as strings, numbers, lists, and even other dictionaries.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
Example :
Dict = {1: 'Goel', 2: 'For', 3: 'Gitm'}
print(Dict)
Output
{1: 'Goel', 2: 'For', 3: 'Gitm'}
Example :
Output
Dictionary with the use of Integer Keys:
{1: 'Gitms', 2: 'For', 3: 'Goels'}
Dictionary with the use of Mixed Keys:
Dr. Yusuf Perwej Page 27
{'Name': 'Goels', 1: [1, 2, 3, 4]}
Python provides the built-in function dict() method which is also used to create the dictionary. An empty
dictionary can be created by just placing curly braces{}.
Example :
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
Output
Empty Dictionary:
{}
Create Dictionary by using dict():
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
Accessing a Dictionary
The values in a dictionary can be accessed by passing the associated key name in a
dictionary[key] syntax:
Example :
coffee_shop = { "cold brew": 3.50, "latte": 4.25, "cappucino": 3.99 }
print(coffee_shop["cold brew"])
Output
3.5
Note:- When a value is retrieved from a key that does not exist, KeyError is raised. If a value is
assigned to a key that doesn’t exist, the new key-value pair will be added. If a value is assigned
to an existing dictionary key, it replaces the existing value.
Nested Dictionaries
Example :
Dict = {1: 'Gitms', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Goels'}}
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
The addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method.
Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise a
new Key with the value is added to the Dictionary.
The code starts with an empty dictionary and then adds key-value pairs to it. It demonstrates
adding elements with various data types, updating a key’s value, and even nesting dictionaries
within the main dictionary. The code shows how to manipulate dictionaries in Python.
Example :
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'Gitms'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
Dr. Yusuf Perwej Page 29
print(Dict)
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'Life', '2': 'Goels'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output:
Empty Dictionary:
{}
In Python Dictionary we have various built-in functions that provide a wide range of operations
for working with dictionaries. These techniques enable efficient manipulation, access, and
transformation of dictionary data.
The clear() method in Python is a built-in method that is used to remove all the elements (key-
value pairs) from a dictionary. It essentially empties the dictionary, leaving it with no key-value
pairs.
Example :
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)
Output
{}
In Python, the get() method is a pre-built dictionary function that enables you to obtain the value
linked to a particular key in a dictionary. It is a secure method to access dictionary values
without causing a KeyError if the key isn’t present.
Example :
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(d.get('Name'))
print(d.get('Gender'))
Output
Ram
None
In Python, the items() method is a built-in dictionary function that retrieves a view object
containing a list of tuples. Each tuple represents a key-value pair from the dictionary. This
method is a convenient way to access both the keys and values of a dictionary simultaneously,
and it is highly efficient.
Example :
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.items())[1][0])
print(list(d.items())[1][1])
Output
Age
19
The keys() method in Python returns a view object with dictionary keys, allowing efficient
access and iteration.
Output
['Name', 'Age', 'Country']
Example :
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.values()))
Output
['Ram', '19', 'India']
Python’s update() method is a built-in dictionary function that updates the key-value pairs of a
dictionary using elements from another dictionary or an iterable of key-value pairs. With this
method, you can include new data or merge it with existing dictionary entries.
Example :
d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d2 = {'Name': 'Neha', 'Age': '22'}
d1.update(d2)
print(d1)
Output
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}
In Python, the pop() method is a pre-existing dictionary method that removes and retrieves the
value linked with a given key from a dictionary. If the key is not present in the dictionary, you
can set an optional default value to be returned.
Example :
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d.pop('Age')
print(d)
Output
{'Name': 'Ram', 'Country': 'India'}
In Python, the popitem() method is a dictionary function that eliminates and returns a random
(key, value) pair from the dictionary.
As opposed to the pop() method which gets rid of a particular key-value pair based on a given
key, popitem() takes out and gives back a pair without requiring a key to be specified.
string
A String is a data structure in Python Programming that represents a sequence of characters. It is
an immutable data type, meaning that once you have created a string, you cannot change it.
Python String are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be represented as text. A
string is a sequence of characters contained within a pair of single quotes (‘ ‘) or double quotes (”
“) and triple double quotes (“”” “””).
The triple quotes can be used to declare multiline strings in Python. Strings can store words,
sentences, or whole paragraphs. They can be any length and can contain letters, numbers, symbols,
and spaces.
Example:
message1 = "I am a string"
message2 = 'I am also a string'
Other data types such as integers, doubles, and Booleans can also be strings if they are wrapped
in quotes. Strings are immutable; they cannot change. Every time an operation is performed on a
string, a new string is created in memory.
# Creating a String
# with single Quotes
String1 = 'Welcome to the Gitm World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Gitm"
print("\nString with the use of Double Quotes: ")
print(String1)
The character of the string can be accessed using the index of the string in a square bracket [
index ]. If we want to access the last character of the string then we can pass the [length of the
string- 1] inside the square bracket.
Output
H
Example:
my_string = "Hello, World!"
first_three_characters = my_string[0:3]
print(first_three_characters)
Output
Hel
Output
World
The below Python functions are used to change the case of the strings. Let’s look at some Python
string methods with examples:
Output
Converted String:
GOELS FOR GITMS
Converted String:
goels for gitms
Converted String:
Goels For Gitms
Converted String:
GOElS fOR GItms
Converted String:
Goels for gitms
Original String
goeLs For giTMS
Here is the list of in-built Python string methods, that you can use to perform actions on string:
Note: All string methods returns new values. They do not change the original string.
1 .capitalize()
The .capitalize() method takes in a string, and returns a copy of the string with the first character
in upper case, and the remaining characters in lower case.
Syntax
"string".capitalize()
Example:
#using capitalize function
print("WELCOME TO LUCKNOW".capitalize())
# initializing a string
text = "welcome to lucknow city"
#using capitalize function
Output
Welcome to lucknow
Welcome to lucknow city
2 .casefold()
The .casefold() method returns a copy of a string with all characters in lowercase. It is similar to
.lower(), but whereas that method deals purely with ASCII text, .casefold() can also convert
Unicode characters.
Syntax
Example:
Below is an example of casefold() being used to set all characters in a string to lowercase:
my_string_1 = "THIS SHOULD ALL BE IN LOWERCASE!"
print(my_string_1.casefold())
output
this should all be in lowercase!
Example:
my_string_2 = "this Should ALSO Be Entirely In Lowercase!"
print(my_string_2.casefold())
output
this should also be entirely in lowercase!
.casefold() can convert a wider scope of characters than .lower() can, including characters unique to
human languages. Take the German lowercase letter “ß”, for example. While .lower() cannot
convert it, .casefold() can convert it to “ss”:
Example:
text = "Straße"
print(text.casefold())
Output
strasse
3 .center()
The .center() string method returns a new string that has been amended with padding. The
padding is allocated evenly to both sides of the string, depending on the overall length specified.
The default padding is whitespace, but any character may be used, including numbers or
symbols.
Syntax
The length parameter is required and must be an integer. This will be the length of new string.
The .center() method accepts an optional 'character' parameter. If no character is specified the
default is whitespace.
Example:
In the following example the .center() method is used to create a string that has a length of 10
characters. The padding character is a ‘+’:
str = "Hello"
new_str = str.center(11, '+')
print(new_str)
output
+++Hello+++
4 .center()
The below example shows what happens when the length parameter specified in the .center()
method isn’t long enough to create a new padded string. The new string is unchanged, as the
length of the original string is less than that of the specified one in the length parameter.
Syntax
string.center(length, 'character')
The length parameter is required and must be an integer. This will be the length of new string.
The .center() method accepts an optional 'character' parameter. If no character is specified the
default is whitespace.
Example:
str1 = "Programming is fun!"
new_str = str1.center(8)
print(new_str)
str = "Hello"
new_str = str.center(12, '+')
print(new_str)
Output
Programming is fun!
+++Hello++++
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
Python, as a versatile programming language, employs various data types to store and manipulate
information. Among these types are mutable and immutable objects, which play a crucial role in
understanding Python’s behaviour in terms of memory management, data manipulation, and
programming paradigms.
Understanding the distinction between mutable and immutable objects is fundamental for Python
developers to write efficient, bug-free, and optimized code. This article aims to delve into the
concept of mutable and immutable objects in Python, elucidating their differences, usage
scenarios, and implications in programming.
A mutable object is an object whose value can be changed after it is created. In other words, the
internal state of the object can be modified without creating a new object.
Lists
Dictionaries
Sets
On the other hand, an immutable object is an object whose value cannot be changed once it is
created. Any operation that appears to modify an immutable object actually creates a new object
with the modified value.
Strings
Numbers
Tuples
As mentioned earlier, mutable objects are those whose value can be changed after creation. This
means that any changes made to the object will modify the object itself, without creating a new
object.
Lists
Lists are a commonly used mutable object in Python. A list can be modified by adding,
removing, or changing elements. The following code demonstrates the mutability of lists in
Python.
Example:
list = [1, 2, 3]
Output:
Explanation:
From the above code, we can easily see that we can add an element, modify any current element,
and can also remove the element from the list. This proves that the lists are mutable in Python.
Dictionaries
Dictionaries are another commonly used mutable object in Python and are used to store key-
value pairs. A dictionary can be modified by adding, removing, or changing key-value pairs.
This can be seen in the code given below.
Example:
dict = {'a': 1, 'b': 2}
print("Original Dictionary: ", dict)
# Adding a key value paper
dict['c'] = 3
print("Dictionary after adding key-value pair: ", dict)
# modifying a value
dict['a'] = 4
print("Dictionary after modifying a value: ", dict)
# removing key value pair
del dict['b']
print("Dictionary after removing element: ", dict)
Output:
Original Dictionary: {'a': 1, 'b': 2}
Dictionary after adding key-value pair: {'a': 1, 'b': 2, 'c': 3}
Dictionary after modifying a value: {'a': 4, 'b': 2, 'c': 3}
Dictionary after removing element: {'a': 4, 'c': 3}
Explanation:
From the above example, it is clear that we can add key-value pairs, modify values, and remove
key-value pairs from a dictionary, all of which modify the dictionary itself. Thus, a Dictionary is
a Mutable Object in Python.
Example:
set = {1, 2, 3}
print("Original set: ", set)
# Adding element in set
set.add(4)
print("Set after adding element: ", set)
# Removing element
set.remove(3)
print("Set after removing element: ", set)
Output:
Original set: {1, 2, 3}
Set after adding element: {1, 2, 3, 4}
Set after removing element: {1, 2, 4}
Explanation:
In the above code, we get no error when we try to add or remove an element from the set which
proves that a set is a mutable object in Python.
Strings
Strings are a commonly used immutable object in Python. A string can be indexed and sliced,
but any attempt to modify a string will result in the creation of a new string object.
Example:
str = "PrepBytes"
# This will result in creation of new object
str += "CollegeGitm"
print(str)
Output:
PrepBytesCollegeGitm
Explanation:
As we can see if we try to concatenate a string. It does not modify the original string. Instead, it
creates a new string object by concatenating the original string with the new string.
Moreover, we cannot modify a particular character from a string. The given code shows what
happens if we try to modify a character in the string.
Example:
str = "PrepBytes"
str[1] = 'a'
Output:
Dr. Yusuf Perwej Page 42
Traceback (most recent call last):
File "a.py", line 2, in
str[1] = 'a'
TypeError: 'str' object does not support item assignment
Explanation:
As we can see, attempting to modify a string will result in a TypeError. Thus, strings are
Immutable in Python.
Numbers
Numbers in Python are also immutable. This means that any attempt to modify a number will
result in the creation of a new number object as shown in the code given below.
Example:
n=5
# The value will not change in place
# in fact, a new number object is created
n += 2
print(n)
Output:
7
Explanation:
Here, in this code, the value of n was not modified in place, but a new number object was
created with the new value.
Tuples
Tuples are another example of an immutable object in Python. The values of tuples cannot be
changed, after their creation. Here’s an example.
Example:
tup = (1, 2, 3)
# This will raise an error because tuples are immutable
tup[1] = 6
Output:
Traceback (most recent call last):
File "a.py", line 4, in
tup[1] = 6
TypeError: 'tuple' object does not support item assignment
Explanation:
As we can see, attempting to modify a tuple will result in a TypeError.
Mutable Immutable
Data type whose values can be changed Data types whose values can’t be
Definition
after creation. changed or altered.
Memory Retains the same memory location even Any modification results in a new
Location after the content is modified. object and new memory location
Example List, Dictionaries, Set Strings, Types, Integer
It is memory-efficient, as no new objects It might be faster in some scenarios
Performance
are created for frequent changes. as there’s no need to track changes.
Not inherently thread-safe. Concurrent
They are inherently thread-safe due
Thread-Safety modification can lead to unpredictable
to their unchangeable nature.
results.
When you need to modify, add, or When you want to ensure data
Use-cases
remove existing data frequently. remains consistent and unaltered.