hey assistent I have a list in python where there are values of -1. how to pop them
- User
hey assistent I have a list in python where there are values of -1. how to pop them
- Assistant
If you want to remove all
-1values from a Python list, you can use a list comprehension or a loop. Below are some approaches you could use:
1. Using List Comprehension
This method creates a new list excluding all the
-1values.my_list = [3, -1, 5, -1, 7, 8, -1] my_list = [x for x in my_list if x != -1] print(my_list)Output:
[3, 5, 7, 8]
2. Using a While Loop with
.remove()This method removes
-1from the list until no-1values remain.my_list = [3, -1, 5, -1, 7, 8, -1] while -1 in my_list: my_list.remove(-1) print(my_list)