I am trying to create a new list inside a looping (without change the name) which will cut all the negative or zero elements, eventually changing its length. Who is the fastest way to do that? I have lost the last days trying to do...
Asked
Active
Viewed 4,166 times
2
-
3Google should provide several answers. I would start by reading this: http://stackoverflow.com/questions/3013449/list-filtering-list-comprehension-vs-lambda-filter – sberry Jan 12 '13 at 18:17
-
1`[i for i in original_list if i > 0]` – Burhan Khalid Jan 12 '13 at 18:23
2 Answers
3
Try using filter:
newlist = filter(lambda a: a>0, [1,2,3])
or
[i for i in original_list if i > 0]
(as mentioned in comments above)

Steve Peak
- 2,657
- 1
- 17
- 18
0
I know it's a religion in python, use lambda or not, but for this simple example I wouldn't use filters.
I personally would prefer a solution with lists and sets:
a = [1,2,-1,0,-1,...] # some list
for i in set(a):
if (i <= 0):
while (a.count(i)>0): a.remove(i)

agim
- 1,841
- 12
- 19
-
That won't work, aside from the performance problems: if there are two `-1` elements, you'll only remove one of them. – DSM Jan 12 '13 at 18:38
-
@DSM Ok the first version wouldn't work, since `a.remove(x)` removes only one element at once, but why do you think lambda functions perform better? – agim Jan 12 '13 at 18:48
-
The problem with your code isn't lambda/no lambda (my preferred solution is the listcomp one). The problem is that you have to (1) scan through the entire list every time you find a negative element, and (2) every time you remove an element from the middle of `a` you have to make a new list, which is very slow. Try both the listcomp solution and yours on, say, `a = range(-10**4, 10**4)`. Your approach will take several thousand times longer. – DSM Jan 12 '13 at 18:53