remove negative numbers from list in python

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.py
original_list = [-1, 2, -3, 4, -5, 6, -7]
new_list = [num for num in original_list if num >= 0]
print(new_list)
112 chars
4 lines

Output:

main.py
[2, 4, 6]
10 chars
2 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