Change language

Python | Filter even values ​​from a list

|

Examples :

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

Method # 1: Using a For Loop
Iterate each item in the list using a for loop and check if num% 2 == 0. If the condition is true, add it to the output list.

# Python code for filtering even values ​​from a list

  
# List initialization

lis = [ 1 , 2 , 3 , 4 , 5 ]

 
# Initialize the output list

out = []

  

for num in lis: 

 

# check status

if num % 2 = = 0

out.append (num)

 

 
# printout

print (out)

Exit:

 [2, 4] 

Method # 2: Using the Bye Loop

# Python code to filter even values ​​from list

 
# List initialization

lis = [ 1 , 2 , 3 , 4 , 5 ]

num = 0

  
# Initialize the output list

out = []

while (num & lt;  len (lis)): 

 

# check status

if lis [num] % 2 = = 0

out.append (lis [ num])

# increment number

num + = 1

 

 
# output to print

print (out)

Exit:

 [2, 4] 

Method # 3: Using comprehension list

# Python code for filtering even values ​​from a list

 
# List initialization

lis = [ 1 , 2 , 3 , 4 , 5 ]

 

lis2 = [i for i in lis if i % 2 = = 0 ]

  
# Printout

print ( lis2)

Exit:

 [ 2, 4] 

Method # 4: Using filter()

# Python code for filtering even values ​​from a list

 
# List initialization

lis1 = [ 1 , 2 , 3 , 4 , 5 ]

 

is_even = lambda x: x % 2 = = 0

 
# using filter

lis2 = list ( filter (is_even, lis1))

  
# Printout

print (lis2)

Exit:

 [2, 4] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method