Signup/Sign In
PUBLISHED ON: JULY 1, 2021

Python program to print odd numbers in a List

In this tutorial, you will learn to write a program that will print all the odd numbers in a list. Odd numbers are the numbers that are not divisible by 2. We will use this property of odd numbers in our program. The concept of loops in Python and conditional statements in Python will be used in our program.

For a given list of numbers, the task is to find and print all the odd numbers in the list.

Input: [2, 7, 4, 10, 8, 6, 9]

Output: [7, 9]

Input: [11, 6, 2, 9, 10, 4, 26, 25]

Output: [11, 9, 25]

Approach to print odd numbers in a List

To execute this program we will follow the approach of traversing the list and checking each element if it is an odd number or not. If it is an odd number, print the number or add it to another list and print this list as output.

Algorithm

Follow the algorithm to understand the approach better

Step 1- Define a function that will check for all odd numbers in a list

Step 2- Declare a list that will store all the odd numbers in a list

Step 3- Run a loop for all elements in the list

Step 4- Check if the element is not divisible by 2

Step 5- If yes, then add the number to the new list

Step 6- Return new list as the output of the function

Step 7- Take input of a list using loop

Step 8- Call the function and print the result

Python Program

Look at the program to understand the implementation of the above-mentioned approach. We have used the append() function to add an element to a list. It is a built-in function.

#odd numbers in list

#function
def odd(list):
    new_list=[]
    for i in list:
        if i%2!=0:               
            new_list.append(i)
    return new_list

#input
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
    e=int(input("Enter element of list "))
    li.append(e)

print("Odd numbers in ",li)
print(odd(li))


Enter size of list 6
Enter element of list 2
Enter element of list 9
Enter element of list 1
Enter element of list 13
Enter element of list 14
Enter element of list 5
Odd numbers in [2, 9, 1, 13, 14, 5]
[9, 1, 13, 5]

Conclusion

In this tutorial, we have learned how to find and print all the odd numbers in a list. We can do the above-mentioned program in a more simple way by just printing the element which satisfies the if condition. Then we will not need to declare a new list and add the odd numbers in that list.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.