I've just started to learn the long-heard python language. I've been working with C before. And I find python, as a modern script language is much concise on various tasks.
So I was wondering, if I have a list foo = [1, 2, 3, 4, 5]
, and I want to pick all the odd numbers out of it into bar
. In C, I might use a loop and check each number in foo
and copy the elements needed into bar
. What do you guys do this "python-style"?
bar = [x for x in foo if x % 2 == 1]
This form is called "list comprehension". In its basic form, it has 4 parts:
What you want to include in the output list. Can be any expression involving the variable(s) defined in the second part (below). In this case, the element x
, unmodified;
A variable, or expression, denoting an element of the input list. Following the for keyword, each element of the list will be bound to that variable (if your list contains complex objects, you can use destructuring assignment to refer only to specific parts of it). In this case, each item of the list is bound to x
;
The input list. Following the in keyword, the list (or other iterable) where you'll get your elements from. In this case, foo
;
A condition that the element must meet to be included in the result (optional). If included, add the keyword if followed by an expression to determine whether or not that element will be included in the output list. In this case, it will be if the number is odd.
filter
function is what you are looking for:
bar = filter(lambda x: x % 2 == 1, foo)
The expression lambda x: x % 2 == 1
is basically equivalent to
def isOdd(x):
return x % 2 == 1
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