Python Program to print largest odd and even number in a list

In this simple python program, we need to sort odd and even numbers in a list. It is an array based python program.

To understand this example, you should have knowledge of the following Python programming topics:

How do we separate odd and even numbers from the list?

In this simple python program, we need to find and print the largest odd and even number from the numbers list. Accept the numbers from the user using a for loop in python and add the elements to the list using the append() method.

Use a for loop to traverse from the start to the end of the list and check whether each element is divisible by 2 without any remainder or remainder is 0 using the mod(%) operator. If the condition is a success, then add that element into another list for even numbers else add that number to the odd list. 

How to find the largest number of the list in python?

Now we have 2 separate lists for odd numbers and even numbers. Then apply the sort() function in python language in which default is ascending order ie., from smallest to largest. We have to find the largest of odd and even numbers so use the keyword reverse=TRUE inside the sort to change the sorting of the list in Descending order. Now, the first element of each list will hold the largest among the odd and even respectively. Output the elements to the user with print() function in python.

ALGORITHM

STEP 1: Accept the number of elements in the list using the input() function in the python programming language.

STEP 2: Initialize a list called num_lst[] and open a for loop to add the elements to the list using the append() function.

STEP 3: initialize two separate lists for odd numbers and even numbers.

STEP 4: Using for loop traverse the list elements and check each element is divisible by 2 ;

  • If yes it is an even number so add that element to even_lst
  • else it will be odd so add that element to odd_lst

STEP 5: Use the sort() method to both odd and even list with keyword reverse=TRUE to sort the elements in Descending order

STEP 6: Print the first element of both odd and even lists to print the largest element.

Python Source Code

                                          n=int(input("Enter the number of list elements: "))

num_lst=[]
even_lst=[]
odd_lst=[]

print("\nEnter list elements:")
for i in range(0,n):
    num_lst.append(int(input()))

for i in num_lst:
    if(i%2==0):
        even_lst.append(i)
    else:
        odd_lst.append(i)
even_lst.sort(reverse=True)
odd_lst.sort(reverse=True)

print("\nLargest even number:",even_lst[0])
print("\nLargest odd number",odd_lst[0])
                                      

OUTPUT

Enter the number of list elements: 6

Enter list elements:
8
4
7
9
10
12

Largest even number: 12

Largest odd number 9