Python Excercises for Interview
Python Excercises for Interview
ipynb - Colab
def sum(a,b):
print("sum of two numbers is",a+b)
def product(a,b):
print("product is",a*b)
Write a Python code to iterate the first 10 numbers, and in each iteration, print the sum of the current and previous number.
for i in range(1,11):
print("current number is ",i, "sum is",i+(i-1))
Write a Python code to accept a string from the user and display characters present at an even index number.
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 1/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
str = input("Enter your string")
for i in str:
if str.index(i) %2 == 0:
print(str[str.index(i)] )
Write a Python code to remove characters from a string from 0 to n and return a new string.
def remove_char(word,n):
print("original word is ",word)
return(word[n:])
Exercise 5: Check if the first and last numbers of a list are the same?
Write a code to return True if the list’s first and last numbers are the same. If the numbers are different, return False.
ls = [10,20,30,40,50]
print(ls[0])
print(ls[-1])
print(ls[:3])
print(ls[2:])
print(ls[:-1])
def check_list(ls):
if ls[0] == ls[-1]:
return True
else:
return False
check_list(ls)
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 2/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
10
50
[10, 20, 30]
[30, 40, 50]
[10, 20, 30, 40]
False
list = [10,12,15,20]
list1=[]
for i in list:
if i %5 ==0:
list1.append(i)
print(list1)
Write a Python code to find how often the substring “Emma” appears in the given string.
22
333
4444
55555
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 3/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
for num in range(6):
for i in range(num):
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Write a Python code to check if the given number is palindrome. A palindrome number is a number that is the same after reverse. For
example, 545 is the palindrome number.
def palindrome(n):
original_num = n
reverse_num = 0
while n >0:
rem = n%10
reverse_num = (reverse_num *10) + rem
n = n//10
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 4/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
if original_num == reverse_num:
print("number is palindrome")
else:
print("number is not a palindrome")
palindrome(n)
Given two lists of numbers, write a Python code to create a new list such that the latest list should contain odd numbers from the first list and
even numbers from the second list.
lst1 = [12,13,14,15,16]
lst2 = [21,22,17,18,20,25]
lst3 = []
for i in lst1:
if i % 2 == 0 :
lst3.append(i)
for i in lst2:
if i %2 !=0:
lst3.append(i)
print(lst3)
Exercise 11: Get each digit from a number in the reverse order.?
For example, If the given integer number is 7536, the output shall be “6 3 5 7“, with a space separating the digits.
given_number = 7536
while given_number>0 :
digit = given_number % 10
given_number = given_number //10
print(digit,end = " ")
6 3 5 7
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 5/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Calculate income tax for the given income by adhering to the rules below
First $10,000 = 0
Next $10,000 = 10
The remaining= 20
Expected Output:
For example, suppose the income is 45000, and the income tax payable is
income = 45000
tax_payble = 0
print("original income is ",income)
if income <= 10000:
tax_payble = 0
elif income <= 20000:
x = (income-10000)
tax_payble = x * 10/100
else:
tax_payble = 0
tax_payble = 10000 * 10/100
tax_payble = tax_payble + (income-20000) * 20/100
print("tax to be paid is",tax_payble)
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 6/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
for i in range(1,11):
for j in range(1,11):
print(i*j, end =" ")
print('\t\t')
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
for j in range(0,i-1):
* * * * *
* * * *
* * *
* *
*
Exercise 15: Get an int value of base raises to the power of exponent
Write a function called exponent(base, exp) that returns an int value of base raises to the power of exp.
def exp(base,expo):
num = expo
result =1
while num>0:
result = result * base
num = num-1
print(base,"raises to the power of",expo,"is",result)
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 7/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Write a program to accept two numbers from the user and calculate multiplication
def mul(input1,input2):
return input1*input2
input1 = int(input("Enter your first number"))
input2 = int(input("Enter your second number"))
mul(input1,input2)
My**Name**Is**James
num = 8
octal_num = ('%o'%num)
print(octal_num)
10
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 8/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
n = 1537.9892
print('%.2f'%n)
1537.99
numbers = []
for i in (0,5):
print("Enter your number at location",i,":")
num = float(input())
numbers.append(num)
print(numbers)
#
Exercise 6: Write all content of a given file into a new file by skipping line number 5
Write a program to take three names as input from a user in the single input() function call.
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 9/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
str1,str2,str3 = input("Enter three strings").split()
print("Name1:",str1)
print("Name2:",str2)
print("Name3:",str3)
Write a program to use string.format() method to format the following three variables as per the expected output
Given:
totalMoney = 1000
quantity = 3
price = 450
Expected Output:
totalMoney = 1000
quantity = 3
price = 450
statement = "I have {1} dollars so i can buy {0} football for {2:.2f} dollars."
print(statement.format(totalMoney,quantity,price))
import os
size = os.path.getsize("text1.txt")
if size == 0:
print("file is empty")
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 10/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
lines = fp.readlines()
print(lines[3])
i = 1
while i <=10:
print(i)
i += 1
1
2
3
4
5
6
7
8
9
10
Write a Python code to print the following number pattern using a loop.
12
123
1234
12345
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 11/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
for i in range(1,6):
for j in range(1,i+1):
print(j,end = ' ')
print(' ')
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Write a Python program to accept a number from a user and calculate the sum of all numbers from 1 to a given number.
For example, if the user entered 10, the output should be 55 (1+2+3+4+5+6+7+8+9+10).
n= 0
m = int(input("Enter your number"))
for i in range(m+1):
n = n+i
i+=1
print(n)
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 12/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Write a Python program to display only those numbers from a list that satisfy the following conditions.
If the number is greater than 150, then skip it and move to the following number.
75
150
145
count = 0
n = int(input("enter your number"))
while n > 0:
n = n//10
count += 1
print(count)
Write a Python program to print the reverse number pattern using a for loop.
54321
4321
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 13/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
321
21
for i in range(6,0,-1):
for j in range(i-1,0,-1):
print(j,end = ' ')
print(' ')
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
for i in range(size,-1,-1):
print(list1[i])
50
40
30
20
10
for i in range(-10,0,1):
print(i)
-10
-9
-8
-7
-6
-5
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 14/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
-4
-3
-2
-1
Exercise 10: Display a message “Done” after the successful execution of the for loop?
for i in range(10):
print(i)
print('Done!')
0
1
2
3
4
5
6
7
8
9
Done!
num1 = 0
num2 = 1
for i in range(10):
print(num1,end = ' ')
result = num1 +num2
num1 = num2
num2 = result
0 1 1 2 3 5 8 13 21 34
Exercise 15: Print elements from a given list present at odd index positions
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 16/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in my_list[1::2]:
print(i,end = ' ')
20 40 60 80 100
Exercise 16: Calculate the cube of all numbers from 1 to a given number?
Write a Python program to print the cube of all numbers from 1 to a given number
Write a program to print the following start pattern using the for loop
*
* *
* * *
* * * *
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 17/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
* * * * *
* * * *
* * *
* *
*
for i in range(0,5):
for j in range(0,i+1):
print("*",end = ' ')
print(' ')
for i in range(5,0,-1):
for j in range(0,i-1):
print("*",end = ' ')
print(' ')
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Write a program to create a function that takes two arguments, name and age,
def f1(name,age):
print(name)
print(age)
f1("Tapan",23)
Tapan
23
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 18/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
def fun1(*args):
for i in args:
print(i,end=' ')
print(' ')
fun1(20,40)
fun1(20,40,60)
20 40
20 40 60
Write a program to create function calculation() such that it can accept two
variables and calculate addition and subtraction. Also, it must return both
def sub_add(a,b):
return a+b,a-b
sub_add(20,10)
(30, 10)
It should accept the employee’s name and salary and display both.
If the salary is missing in the function call then assign default value 9000 to salary
def show_employee(name,salary=9000):
print(f"your name is {name}")
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 19/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
print(f"your salary is {salary}")
show_employee("Tapan",40000)
show_employee("Pati")
Exercise 5: Create an inner function to calculate the addition in the following way
Create an inner function inside an outer function that will calculate the addition of a and b.
At last, an outer function will add 5 into addition and return it.
def outer(a,b):
square = a**2
def inner(a,b):
return a+b
add = inner(3,2)
return add+5
result = outer(5,10)
print(result)
10
Write a program to create a recursive function to calculate the sum of numbers from 0 to 10.
def addition(num):
if num:
return num+addition(num-1)
else:
return 0
addition(55)
1540
Exercise 7: Assign a different name to function and call it through the new name
def display_student(name,age):
print(name)
print(age)
show_student = display_student
show_student("Tapan",23)
Tapan
23
Exercise 8: Generate a Python list of all the even numbers between 4 to 30?
lst = []
def gen():
for i in range(4,30,2):
lst.append(i)
return lst
l = gen()
print(l)
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
greater is 24
Exercise 1A: Create a string made of the first, middle and last character?
Write a program to create a new string made of an input string’s first, middle, and last character.
str = 'james'
result = str[0]
mi = int(len(str)/2)
result = result + str[mi]
result = result + str[-1]
print(result)
jms
Write a program to create a new string made of the middle three characters of an input string.
str = 'Tapankumar'
mi = int(len(str)/2)
result = str[mi-1] + str[mi] + str[mi+1]
print(result)
nku
Given two strings, s1 and s2. Write a program to create a new string s3 by
def fun(str1,str2):
print("original strings are",str1,str2)
mi = int(len(str1)/2)
x = str1[:mi:]
print(x)
x = x+ str2
x= x+ str1[mi:]
print("after appending the string",x)
fun('Tapan','pati')
Exercise 3: Create a new string made of the first, middle, and last characters of each input string?
Given two strings, s1 and s2, write a program to return a new string made of s1 and s2’s first, middle, and last characters.
s1 = 'Tapan'
s2 = 'pati'
mi_s1= int(len(s1)/2)
mi_s2 = int(len(s2)/2)
new_s = s1[0]+s2[0]+s1[mi_s1]+s2[mi_s2]+s1[-1]+s2[-1]
print(new_s)
Tpptni
Exercise 4: Arrange string characters such that lowercase letters should come first?
Given string contains a combination of the lower and upper case letters. Write
str1 = "TapanKumarPati"
lower =[]
upper =[]
for char in str1:
if char.islower():
lower.append(char)
else:
upper.append(char)
sorted_str = ''.join(lower+upper)
print("Result",sorted_str)
Result apanumaratiTKP
Exercise 5: Count all letters, digits, and special symbols from a given string
def count(str):
char_count = 0
digit_count = 0
symbol_count = 0
for char in str:
if char.isalpha():
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 23/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
char_count += 1
elif char.isdigit():
digit_count += 1
else:
symbol_count+=1
print(f"The number of characaters {char_count},The number of digits{digit_count},The number of symbol{symbol_count}")
count("Tapan@123")
Given two strings, s1 and s2. Write a program to create a new string s3 made of
the first char of s1, then the last char of s2, Next, the second char of s1 and
second last char of s2, and so on. Any leftover chars go at the end of the
result.
s1 = "Tapan"
s2 = "Pati"
len1 = len(s1)
len2 = len(s2)
for i in range(length):
if i < len1 :
result = result + s1[i]
if i < len2:
result = result + s2[i]
print(result)
TiatpaaPn
Write a program to check if two strings are balanced. For example, strings s1
and s2 are balanced if all the characters in the s1 are present in s2. The
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 24/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
str1 ="Tapan"
str2 = "napTap"
for i in str1:
for j in str2:
if i == j:
pass
print("Two strings are balanced")
Exercise 8: Find all occurrences of a substring in a given string by ignoring the case
Write a program to find all occurrences of “USA” in a given string ignoring the case.
Exercise 9: Calculate the sum and average of the digits present in a string
Given a string s1, write a program to return the sum and average of the digits that appear in the string, ignoring all other characters.
str1 = "PYnative29@#8496"
sum = 0
count = 0
for i in str1:
if i.isdigit():
sum += int(i)
count += 1
avg = sum/count
print("sum is ",sum)
print("average is",avg)
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 25/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
sum is 38
average is 6.333333333333333
Exercise 10: Write a program to count occurrences of all characters within a string
str1 = "Apple"
char_dict = {}
char_dict[char] = count
print('Result:', char_dict)
str1 ="Tapan"
rev_str1 = str1[::-1]
print(rev_str1)
napaT
Write a program to find the last position of a substring “Emma” in a given string.
str1 = "Emma is a data scientist who knows Python. Emma works at google."
print("original string",str1)
index = str1.rfind('Emma')
print("Emaa index is",index)
original string Emma is a data scientist who knows Python. Emma works at google.
Emaa index is 43
Write a program to split a given string on hyphens and display each substring.
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 26/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
str1 = "Emma-is-a-data-scientist"
str2 = str1.split('-')
print(str2)
import re
str1 = "/*Jon is @developer & musician"
result = re.sub(r'[^\w\s]','',str1)
print(result)
import re
str1 = 'I am 25 years and 10 months old'
result = "".join([i for i in str1 if i.isdigit()])
print(result)
2510
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 27/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Write a program to find words with both alphabets and numbers from an input string.
res = []
# split string on whitespace
temp = str1.split()
Exercise 18: Replace each special symbol with # in the following string
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 28/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-cd9e3422ffd1> in <cell line: 2>()
1 string = '/*Jon is @developer & musician!!'
----> 2 print("The original string is : ", str1)
3
4 # Replace punctuations with #
5 replace_char = '#'
Write a program to remove the item present at index 4 and add it to the 2nd position and at the end of the list.
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 29/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
91
[54, 44, 91, 27, 79, 41]
[54, 44, 91, 27, 79, 41, 91]
Exercise 3: Slice list into 3 equal chunks and reverse each chunk?
def slice_reverse(sample_list):
try:
if len(sample_list) % 3 != 0:
print("Must be divisible by zero")
length = len(sample_list)
chunk_size = length//3
chunks = [sample_list[i:i+chunk_size] for i in range(0,length,chunk_size)]
reversed_chunks = [chunk[::-1] for chunk in chunks]
return reversed_chunks
except Exception as e:
print(f"error {e}")
print(result)
Write a program to iterate a given list and count the occurrence of each element and create a dictionary to show the count of each element.
count_dict = {}
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 30/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Exercise 5: Create a Python set such that it shows the element from both lists in a pair?
first_list = [2, 3, 4, 5, 6, 7, 8]
second_list = [4, 9, 16, 25, 36, 49, 64]
result = zip(first_list,second_list)
set_result = set(result)
print(set_result)
{(7, 49), (2, 4), (4, 16), (8, 64), (6, 36), (3, 9), (5, 25)}
Exercise 6: Find the intersection (common) of two sets and remove those elements from the first set?
Exercise 7: Checks if one set is a subset or superset of another set. If found, delete all elements from that set?
if first_set.issubset(second_set):
first_set.clear()
elif second_set.issubset(first_set):
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 31/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
second_set.clear()
print(first_set)
print(second_set)
Exercise 8: Iterate a given list and check if a given element exists as a key’s value in a dictionary. If not, delete it from the list?
Exercise 9: Get all values from the dictionary and add them to a list but don’t add duplicates?
speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}
l1 =[]
for value in speed.values():
if value not in l1:
l1.append(value)
print(l1)
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 32/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Exercise 10: Remove duplicates from a list and create a tuple and find the minimum and maximum number?
Write a program to add two lists index-wise. Create a new list that contains the 0th index item from both the list, then the 1st index item, and
so on till the last element. any leftover items will get added at the end of the new list.
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 33/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Given a list of numbers. write a program to turn every item of a list into its square.?
l1 =[1,2,3,4]
print(list(map(lambda x: x**2,l1)))
[1, 4, 9, 16]
Given a two Python list. Write a program to iterate both lists simultaneously and display items from list1 in original order and items from list2
in reverse order
10 400
20 300
30 200
40 100
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 34/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Write a program to add item 7000 after 6000 in the following Python List?
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].append(7000)
print(list1)
[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
You have given a nested list. Write a program to extend it by adding the sublist ["h", "i", "j"] in such a way that it will look like the following list.
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
['a', 'b', ['c', ['d', 'e', ['f', 'g'], 'k'], 'l'], 'm', 'n', 'h', 'i', 'j']
You have given a Python list. Write a program to find value 20 in the list, and if it is present, replace it with 200. Only update the first
occurrence of an item
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 35/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
print(list1)
Given a Python list, write a program to remove all occurrences of item 20.
dict4 = dict1.update(dict2)
print(dict1)
dict3 = {**dict1, **dict2}
print(dict3)
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 36/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Exercise 3: Print the value of key ‘history’ from the below dict
sampleDict = {
"class": {
"student": {
"name": "Mike",
"marks": {
"physics": 70,
"history": 80
}
}
}
}
print(sampleDict["class"]["student"]["marks"]["history"])
80
{'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma': {'designation': 'Developer', 'salary': 8000}}
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
# Keys to extract
keys = ["name", "salary"]
new_dict = {k: sample_dict[k] for k in keys}
print(new_dict)
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 37/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}
# Keys to remove
keys = ["name", "salary"]
for k in keys:
sample_dict.pop(k)
print(sample_dict)
Write a Python program to check if value 200 exists in the following dictionary.
V is present
sample_dict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 38/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
sample_dict["location"] = sample_dict.pop("city")
print(sample_dict)
Exercise 9: Get the key of a minimum value from the following dictionary?
sample_dict = {
'Physics': 82,
'Math': 65,
'history': 75
}
print(min(sample_dict,key = sample_dict.get))
Math
Write a Python program to change Brad’s salary to 8500 in the following dictionary.
sample_dict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 500}
}
sample_dict['emp3']['salary'] = 8500
print(sample_dict)
{'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma', 'salary': 8000}, 'emp3': {'name': 'Brad', 'salary': 8500}}
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 39/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
Write a Python program to return a new set with unique items from both sets by removing duplicates.
Exercise 4: Update the first set with items that don’t exist in the second set
Given two Python sets, write a Python program to update the first set with items that exist only in the first set and not in the second set.
{10, 30}
Write a Python program to remove items 10, 20, 30 from the following set at once.
{50, 40}
Exercise 7: Check if two sets have any elements in common. If yes, display the common elements
{10}
Exercise 8: Update set1 by adding items from set2, except common items
Exercise 9: Remove items from set1 that are not common to both set1 and set2
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 41/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
The given tuple is a nested tuple. write a Python program to print the value 20.
20
tupl1= (50,)
print(tupl1)
(50,)
Write a program to unpack the following tuple into four variables and display each variable.
10
20
30
40
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 42/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
(99, 88)
(11, 22)
Write a program to copy elements 44 and 55 from the following tuple into a new tuple.
(44, 55)
Given is a nested tuple. Write a program to modify the first item (22) of a list inside a following tuple to 222
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 43/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
[50, 50]
2
Exercise 10: Check if all items in the tuple are the same
import datetime
print(datetime.datetime.now())
2025-01-06 12:48:34.642580
2025-01-06 16:20:00
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 44/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
2024-12-30 00:00:00
given_date = datetime(2025, 1, 6)
print(given_date.strftime('%A %d %B %Y'))
given_date = datetime(2025, 1, 6)
print(given_date.today().weekday())
print(given_date.strftime('%A'))
0
Monday
2025-01-13 10:00:00
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 45/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
import time
1736170092404
2020-02-25 00:00:00
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 46/46