Skip to content
Related Articles

Related Articles

Python | Filter even values from a list
  • Last Updated : 14 Feb, 2019

Given a list of numbers, the task is to make a new list containing only even values.

Examples:

Input: list = [1, 2, 3, 4, 5]
Output: [2, 4]

Input: list = [12, 14, 95, 3]
Output: [12, 14]

 
Method #1 : Using For loop
Iterate each element in the list using for loop and check if num % 2 == 0. If the condition satisfies, then append it in output list.




# Python code to filter even values from a list
  
# Initialisation of list
lis = [1,2,3,4,5]
  
# Output list initialisation
out = []
  
for num in lis: 
      
    # checking condition 
    if num % 2 == 0
        out.append(num)
          
  
# printing output
print(out)


Output:

[2, 4]

 
Method #2 : Using While loop






# Python code to filter even values from a list
  
# Initialisation of list
lis = [1,2,3,4,5]
num = 0
  
# Output list initialisation
out = []
while(num < len(lis)): 
      
    # checking condition 
    if lis[num] % 2 == 0
        out.append(lis[num])
    # increment num 
    num += 1
  
  
# printing output
print(out)


Output:

[2, 4]

 
Method #3 : Using list Comprehension




# Python code to filter even values from a list
  
# Initialisation of list
lis = [1,2,3,4,5]
  
lis2 = [i for i in lis if i%2 == 0]
  
# Printing output
print(lis2)


Output:

[2, 4]

 
Method #4 : Using filter()




# Python code to filter even values from a list
  
# Initialisation of list
lis1 = [1,2,3,4,5]
  
is_even = lambda x: x % 2 == 0
  
# using filter
lis2 = list(filter(is_even, lis1))
  
# Printing output
print(lis2)


Output:

[2, 4]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :