Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip elements on a condition based in a list comprehension in python

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.

like image 278
Vinodh Velumayil Avatar asked Jan 04 '17 15:01

Vinodh Velumayil


People also ask

How do you skip element in a list Python?

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 .

Can you put an if statement in a list comprehension?

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.

Which is faster for loop or list comprehension?

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.

Can we use else in list comprehension Python?

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.


1 Answers

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))
like image 184
ettanany Avatar answered Sep 17 '22 01:09

ettanany