Python program to find the second largest element, the cumulative sum of elements

 

Python program to find the second largest element, even and odd elements, the cumulative sum of elements

Problem definition:

Read the elements of the list from the user and find 1) find the second largest element 2) form two separate lists to store even and odd elements of the original list and 3) Create a new list with a cumulative sum of elements of the original list.

Solution

Python program to find the second largest element of a list.

l1 = list()

n1 = int(input("Enter the number of elements of list:"))
for i in range(n1):
    ele = int(input("Enter the element:"))
    l1.append(ele)

print("List is: ",l1)
l1.sort()
print("List after sort is: ",l1)
print ("Second largest element is:", l1[n1-2])

Output

Enter the number of elements in first list:4
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
List is:  [1, 2, 3, 4]
List after sort is:  [1, 2, 3, 4]
Second largest element is: 3

Python program to create two separate lists to store odd and even elements of the original list.

l1 = list()
even = list()
odd = list()

n1 = int(input("Enter the number of elements of list:"))
for i in range(n1):
    ele = int(input("Enter the element:"))
    l1.append(ele)

print("First list is: ",l1)

for ele in l1:
    if ele % 2 == 0:
        even.append(ele)
    else:
        odd.append(ele)
        
print ("Even list is:", even)
print ("Odd list is:", odd)

Output

Enter the number of elements of list:5
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
Enter the element:5
First list is:  [1, 2, 3, 4, 5]
Even list is: [2, 4]
Odd list is: [1, 3, 5]

Python program to create a list with a cumulative sum of elements of the original list.

l1 = list()
l2 = list()
sum = 0
n1 = int(input("Enter the number of elements in first list:"))
for i in range(n1):
    ele = int(input("Enter the element:"))
    l1.append(ele)

print("List 1 is: ",l1)

for ele in l1:
    sum = sum + ele
    l2.append(sum)
    
print ("List 2 is: ", l2)

Output

Enter the number of elements in first list:4
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
List 1 is:  [1, 2, 3, 4]
List 2 is:  [1, 3, 6, 10]

Summary:

This tutorial discusses the Python program to find the second largest element, even and odd elements, the cumulative sum of elements. If you like the program please share it with your friends and share your opinion in the comment box. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *