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
- Using For Loop
- Using While Loop
- Using Lambda Expressions
- Using Pass
- Using Enumerate Function
- Using List Comprehension
- Using Recursion
# 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
# 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
# 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]
# 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
# 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
# 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]
# 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
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.