I have a list List:
List = [-2,9,4,-6,7,0,1,-4]
For numbers less than zero (0) in the list , I would like to skip those numbers and form another list.
Example:-
List = [9,4,7,0,1]
This is a kind of doubt I have, not sure If we can achieve. If it's possible to achieve, can anyone please post here.
How do you skip an element in Python? Use iter() and next() to skip first element of a for-loop User iter(object) to return an iterable for any iterable object . Call next(iterator) on iterator as the iterable for object to skip the first element of iterator .
You can add an if statement at the end of a list comprehension to return only items which satisfy a certain condition. For example, the code below returns only the numbers in the list that are greater than two.
List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
Answer. Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension.
You have many options to achieve that. With a list comprehension you can do:
my_list = [i for i in my_list if i>=0]
With filter()
:
my_list = filter(lambda i: i>=0, my_list)
Note:
In Python 3, filter()
returns a filter
object (not list
), to convert it to a list, you can do:
my_list = list(filter(lambda i: i>=0, my_list))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With