To remove negative numbers from a list in python, we can use filtering. Filtering is a process of selecting specific items from a sequence based on certain conditions. In this case, we want to select all the items that are greater than or equal to zero.
Here's the code:
main.py112 chars4 lines
Output:
main.py10 chars2 lines
Here, we first define a list of numbers called original_list
. Then we create a new list called new_list
using list comprehension. We iterate over each item in the original_list
and only add it to new_list
if it's greater than or equal to zero.
Finally, we print out the new_list
which contains only the non-negative numbers from the original_list
.
gistlibby LogSnag