Class 24 8
Class 24 8
G Pranav - CB.EN.U4AIE22016
1. Python program to interchange first and last element in a list
#1
list = [1,2,3,4,5]
list[0],list[-1] = list[-1],list[0]
print(list)
[5, 2, 3, 4, 1]
element = 5
list = [1,2,3,4,5]
if element in list:
print("Yeah")
else:
print("Nah")
Yeah
list = [1,2,3,-4,5]
print(min(list))
-4
list = [1,2,3,4,5]
even,odd = 0,0
for i in list:
if i%2 == 0:
even+=1
else:
odd+=1
print(f"There are {even} numbers and {odd} odd numbers")
list = [1,2,3,4,5]
print(list[0:4])
[1, 2, 3, 4]
print(list3)
print(list4)
Dictionary Questions
1. Write a python program to sort a dictionary by value
#1
print(dict1_ascending)
print(dict1_descending)
print()
print(dict2_ascending)
print(dict2_descending)
for i in dict.values():
sum = sum + i
sum
Y
A
1. Find the count of each key, value, and key value pair
#4
freqency_dict
{1: 2, 2: 2, 3: 1, 4: 1}
4
8
12
16
20
24
28
32
36
40
Q2. Write a program to compute the sum of the series: 1+𝑥+𝑥^2+…+𝑥^𝑛 Let the user input x
and n.
x = int(input("Enter x: "))
n = int(input("Enter n: "))
sum = 0
for i in range(n+1):
sum += (x**i)
print(sum)
s = "StRinG"
s1 = ""
for i in s:
if ord(i) >= 65 and ord(i) <= 90:
i = chr(ord(i) + 32)
else:
i = chr(ord(i) - 32)
s1+=i;
s1
'sTrINg'
Q4. Write a program to display the elements and their locations which are not multiples of 2 or
3. The list must be user input.
for i in range(len(list)):
if not (list[i]%2 == 0 or list[i]%3 == 0):
print (f"{list[i]} at position {i}")
1 at position 0
5 at position 3
7 at position 5
print(list[::-1])
[7, 6, 5, 4, 3, 2, 1]