Signup/Sign In

Python program to print even numbers in a list

In this tutorial, you will learn to write a program that will print all the even numbers in a list. Even numbers are the numbers that are divisible by 2. We will use this property of even 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 even numbers in the list.

Input: [7, 4, 9, 3, 5, 1, 2, 12]

Output: [4, 2, 12]

Input: [13, 17, 9, 8, 15, 29]

Output: [8]

Approach to print even 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 even number or not. If it is an even 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 even numbers in a list

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

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

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

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.

#even numbers in list

#function
def even(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("Even numbers in ",li)
print(even(li))


Enter size of list 5
Enter element of list 3
Enter element of list 6
Enter element of list 1
Enter element of list 2
Enter element of list 9
Even numbers in [3, 6, 1, 2, 9]
[6, 2]

Conclusion

In this tutorial, we have learned how to find and print all the even 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 even 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.