Python | Filter even values from a list

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

[2, 4]

 
Method #2 : Using While loop

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

[2, 4]

 
Method #3 : Using list Comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

[2, 4]

 
Method #4 : Using filter()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

[2, 4]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.