VOOZH about

URL: https://www.geeksforgeeks.org/python/python-remove-negative-elements-in-list/

⇱ Remove Negative Elements in List-Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove Negative Elements in List-Python

Last Updated : 15 Jul, 2025

The task of removing negative elements from a list in Python involves filtering out all values that are less than zero, leaving only non-negative numbers. Given a list of integers, the goal is to iterate through the elements, check for positivity and construct a new list containing only positive numbers. For example, if a = [5, 6, -3, -8, 9, 11, -12, 2], the resulting list after removing negative numbers would be [5, 6, 9, 11, 2].

Using list comprehension

List comprehension is the most concise and Pythonic way to filter out negative numbers. It iterates through the list, applying a condition (ele > 0) to include only positive values. This method is widely used due to its readability and efficiency in handling small to moderately large lists.


Output
[5, 6, 9, 11, 2]

Explanation: list comprehension iterates through each element, keeping only those greater than 0, and stores them in res.

Using filter()

filter() applies a boolean condition (lambda x: x > 0) to each element, returning an iterator with only positive numbers. It is a functional programming approach that enhances code clarity and efficiency, especially when working with built-in filtering methods.


Output
[5, 6, 9, 11, 2]

Explanation: filter() with a lambda function to retain only positive numbers from a, converting the result to a list.

Using itertools.compress()

compress() filters a list based on a predefined boolean mask ([x > 0 for x in a]). It is useful when working with complex filtering conditions or when a separate boolean mask needs to be used for multiple operations. While not as common as list comprehension, it is an optimized method for selective filtering.


Output
[5, 6, 9, 11, 2]

Explanation: itertools.compress() with a boolean mask to filter out negative numbers. The mask [x > 0 for x in a] marks positives as True and compress(a, mask) retains only those values.

Using numpy

NumPy provides an optimized, vectorized approach for filtering numerical data. Using a[a > 0] efficiently extracts positive elements without explicit loops. This method is ideal for large datasets, offering high-speed performance compared to traditional Python lists.


Output
[5, 6, 9, 11, 2]

Explanation: This code selects only positive numbers from a using NumPy's indexing (a[a > 0]), which is faster than loops. The result is then converted into a list using .tolist().

Comment