Page 231 - Information_Practice_Fliipbook_Class11
P. 231
largestElement = secondLargestElement = float('-inf')
for element in myList:
if element > largestElement:
secondLargestElement = largestElement
largestElement = element
elif element > secondLargestElement and element != largestElement:
secondLargestElement = element
if secondLargestElement is not None:
print(f"The largest element in the list is: {largestElement}")
print(f"The second largest element in the list is: {secondLargestElement}")
else:
print("List has fewer than two elements.")
4. Write a program to read a list of n integers and find their median.
Note: The median value of a list of values is the middle one when they are arranged in order. If there are two middle values then take
their average.
Hint: Use an inbuilt function to sort the list.
Ans. n = int(input("Enter the number of integers: "))
inputList = []
for i in range(n):
num = int(input(f"Enter integer {i + 1}: "))
inputList.append(num)
sortedList = sorted(inputList)
n = len(sortedList)
if n % 2 == 0:
mid1 = sortedList[n // 2 - 1]
mid2 = sortedList[n // 2]
median = (mid1 + mid2) / 2
else:
median = sortedList[n // 2]
print("\nOriginal List:", inputList)
print("Median:", median)
5. Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements i.e. all elements occurring
multiple times in the list should appear only once.
Ans. myList = eval(input('Enter the list:\n'))
resultList = []
for element in myList:
if element not in resultList:
resultList.append(element)
print('Original List:', myList)
print('List with no duplicates:' , resultList)
6. Write a program to create a list of elements. Input an element from the user that has to be inserted in the list. Also input the position at
which it is to be inserted.
Ans. n = int(input("Enter the number of elements in the list: "))
Python Dictionaries 217

