Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Ruby's .select

Tags:

python

ruby

I have an list/array, lets call it x, and I want to create a new list/array, lets call this one z, out of elements from x that match a certain condition.

In Ruby you could do that by calling the .select method on the list/array like so:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
z = x.select{|a| a < 5}

After this z would look like this:

z = [1, 2, 3, 4]

Is there a function/method in Python that I could use to get the same effect?

If not, what is the cleanest way I could do this?

like image 801
tperera11 Avatar asked Aug 26 '15 04:08

tperera11


3 Answers

Python has a built-in filter function:

lst = [1, 2, 3, 4, 5, 6]
filtered = filter(lambda x: x < 5, lst)

But list comprehensions might flow better, especially when combining with map operations:

mapped_and_filtered = [x*2 for x in lst if x < 5]
# compare to:
mapped_and_filtered = map(lambda y: y*2, filter(lambda x: x < 5, lst))
like image 165
Platinum Azure Avatar answered Sep 21 '22 15:09

Platinum Azure


One option is to use list comprehension:

>>> [a for a in x if a < 5]
[1, 2, 3, 4]
like image 41
Yu Hao Avatar answered Sep 19 '22 15:09

Yu Hao


Using a list comprehension is considered "Pythonic":

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
z = [i for i in x if i < 5]
print z

Output

[1, 2, 3, 4]
like image 39
mhawke Avatar answered Sep 19 '22 15:09

mhawke