Python Print Even Numbers in a List

In this snippet, we'll print all even numbers in the given list.

# given list
myList = [5, 10, 14, 25, 30]

# output
10 14 30

Table of Contents

  1. Using For Loop
  2. Using While Loop
  3. Using Lambda Expressions
  4. Using Pass
  5. Using Enumerate Function
  6. Using List Comprehension
  7. Using Recursion

Using For Loop

# list of numbers
myList = [5, 10, 14, 25, 30]

# iterating each number in list
for num in myList:
    # checking condition
    if num % 2 == 0:
        print(num, end=" ")

Output:

10 14 30

Using While Loop

# list of numbers
myList = [5, 10, 14, 25, 30]
num = 0

# iterating each number in list
while num < len(myList):

    # checking condition
    if myList[num] % 2 == 0:
        print(myList[num], end=" ")

    # increment num
    num  = 1

Output:

10 14 30

Using Lambda Expressions

# list of numbers
myList = [5, 10, 14, 25, 30]

# lambda expression
even_numbers = list(filter(lambda x: (x % 2 == 0), myList))

print("Even numbers: ", even_numbers)

Output:

Even numbers:  [10, 14, 30]

Using Pass

# list of numbers
myList = [5, 10, 14, 25, 30]

for i in myList:
    if i % 2 != 0:
        pass
    else:
        print(i, end=" ")

Output:

10 14 30

Using Enumerate Function

# list of numbers
myList = [5, 10, 14, 25, 30]

for a, i in enumerate(myList):
    if i % 2 == 0:
        print(i, end=" ")

Output:

10 14 30

Using List Comprehension

# list of numbers
myList = [5, 10, 14, 25, 30]

even_numbers = [num for num in myList if num % 2 == 0]

print("Even numbers: ", even_numbers)

Output:

Even numbers:  [10, 14, 30]

Using Recursion

# list of numbers
myList = [5, 10, 14, 25, 30]

# recursive function
def evenNumbers(list, n=0):
    # base case
    if n == len(list):
        exit()
    if list[n] % 2 == 0:
        print(list[n], end=" ")

    # call function
    evenNumbers(list, n   1)

print("Even numbers:")
evenNumbers(myList)

Output:

Even numbers:
10 14 30