Python – Remove Negative Elements in List

Sometimes, while working with Python lists, we can have a problem in which we need to remove all the negative elements from list. This kind of problem can have application in many domains such as school programming and web development. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [6, 4, 3]
Output : [6, 4, 3]

Input : test_list = [-6, -4]
Output : []

Method #1 : Using list comprehension
The combination of above functions can be used to solve this problem. In this, we perform the task of removing negative elements by iteration in one liner using list comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove Negative Elements in List
# Using list comprehension
  
# initializing list
test_list = [5, 6, -3, -8, 9, 11, -12, 2
  
# printing original list
print("The original list is : " + str(test_list))
  
# Remove Negative Elements in List
# Using list comprehension
res = [ele for ele in test_list if ele > 0]
  
# printing result 
print("List after filtering : " + str(res))

chevron_right


Output :



The original list is : [5, 6, -3, -8, 9, 11, -12, 2]
List after filtering : [5, 6, 9, 11, 2]

 

Method #2 : Using filter() + lambda
The combination of above functions can also offer an alternative to this problem. In this, we extend logic of retaining positive formed using lambda function and extended using filter().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove Negative Elements in List
# Using filter() + lambda
  
# initializing list
test_list = [5, 6, -3, -8, 9, 11, -12, 2
  
# printing original list
print("The original list is : " + str(test_list))
  
# Remove Negative Elements in List
# Using filter() + lambda
res = list(filter(lambda x : x > 0, test_list))
  
# printing result 
print("List after filtering : " + str(res))

chevron_right


Output :

The original list is : [5, 6, -3, -8, 9, 11, -12, 2]
List after filtering : [5, 6, 9, 11, 2]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.