Professional Documents
Culture Documents
Erecord David 4 Python
Erecord David 4 Python
EX NO:4
List in Python
29.1.23
1. Write a Python program to find the second smallest and second largest
number in a list
Aim:
To write a Python program to find the second smallest and Second largest number in a list
Algorithm:
Step 1: Start the program.
Step 3: find the length of the list using len() method and store it in ‘n’.
Step 4: the second largest element will be in the index (n-2),the second smallest element will be in the
index 1.
Program:
list = [12, 45, 2, 41, 31, 10, 8, 6, 4]
list.sort()
n=len(list)
Output:
2. Write a Python program to get the frequency of the elements in a list
Aim:
Algorithm:
Step 3: Use for loop to print the elements along with its frequency of occurrence using count()
methods
Step 4: As we traverse through the for loop, append each element to the empty list n. and for every
iteration compare current elements with n to avoid repetition.
Program:
List= [1, 2, 8, 3, 2, 2, 2, 5, 1]
n=[]
for x in List:
if x not in n:
print(x,"|",List.count(x))
n.append(x)
Output:
3. Write a Python program to remove duplicate elements in a list.
Aim:
To write a Python program to remove duplicate elements in a list.
Algorithm:
Step 1: Start the program.
Step 4: print the set ‘x’, in python set doesn’t recognize duplicate elements. Only unique elements will
be printed
Program:
a = [10,20,30,20,10,50,60,40,80,50,40]
x=set(a)
print(x)
Output:
Aim:
To Write a python program to generate 10 random numbers from 1 to 50 and insert them into a list.
Algorithm:
Step 1: Start the program.
Step 3: read the number of elements from the user and store it in variable n.
Step 5: use for loop to generate random numbers using randint() or randrange() functions of the
random module.
Step 6: insert these random numbers to the list random_list
Program:
import random
random_list=[]
pos=0
for x in range(1,n+1):
rand=random.randint(1,51)
random_list.insert(pos,rand)
pos+=1
print("Randomized list=",random_list)
Output:
Aim:
To write a python program to print each and every element in reverse order.
Algorithm:
Step 1: Start the program.
list = [4, 5, 6, 7, 8, 9]
print("Output:",list[::-1])
Output:
Result:
These programs are executed successfully and the result is displayed on the screen