Python | Filter even values from a list
Last Updated :
05 May, 2023
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 the output list.
Python3
lis = [ 1 , 2 , 3 , 4 , 5 ]
out = []
for num in lis:
if num % 2 = = 0 :
out.append(num)
print (out)
|
Time complexity: O(n) – It will iterate through each element of the list once.
Auxiliary space: O(m) – It will create a new list ‘out’ to store the even numbers, which could potentially be as large as the original list. Therefore, the space complexity is linear with respect to the size of the input list.
Method #2: Using While loop
Python3
lis = [ 1 , 2 , 3 , 4 , 5 ]
num = 0
out = []
while (num & lt
len (lis)):
if lis[num] % 2 = = 0 :
out.append(lis[num])
num + = 1
print (out)
|
Time complexity: O(n) – It will iterate through each element of the list once.
Auxiliary space: O(m) – It will create a new list ‘out’ to store the even numbers, which could potentially be as large as the original list. Therefore, the space complexity is linear with respect to the size of the input list.
Method #3: Using list Comprehension
Python3
lis = [ 1 , 2 , 3 , 4 , 5 ]
lis2 = [i for i in lis if i % 2 = = 0 ]
print (lis2)
|
Time Complexity: O(n), where n is length of lis list.
Auxiliary Space: O(n), where n is length of lis2 list.
Method #4 : Using filter()
Python3
lis1 = [ 1 , 2 , 3 , 4 , 5 ]
def is_even(x): return x % 2 = = 0
lis2 = list ( filter (is_even, lis1))
print (lis2)
|
Method#5: Using numpy.array()
Python3
import numpy as np
lis1 = np.array([ 1 , 2 , 3 , 4 , 5 ])
is_even = lis1[lis1 % 2 = = 0 ]
print (is_even)
|
Output:
[2 4]
Method#6: Using a generator function
Approach is using a function that returns a generator. Generators are a type of iterable, like lists or tuples, but instead of creating the entire sequence in memory at once, they generate the values one at a time, on the fly. This can be useful when working with large lists or when the values in the list are expensive to compute.
Here is an example of how you could use a generator function to filter even values from a list:
Python3
def even_values(lst):
for value in lst:
if value % 2 = = 0 :
yield value
evens = list (even_values([ 1 , 2 , 3 , 4 , 5 ]))
print (evens)
|
The time complexity of the generator function even_values is O(n), since it needs to iterate over all n elements of the list. The space complexity is also O(n), since it stores all of the even values in the list evens.
Share your thoughts in the comments
Please Login to comment...