Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python have a shorthand for this simple task?

Tags:

python

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"?

like image 825
xzhu Avatar asked Feb 12 '12 06:02

xzhu


2 Answers

bar = [x for x in foo if x % 2 == 1]

This form is called "list comprehension". In its basic form, it has 4 parts:

  1. 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;

  2. 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;

  3. The input list. Following the in keyword, the list (or other iterable) where you'll get your elements from. In this case, foo;

  4. 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.

like image 155
mgibsonbr Avatar answered Oct 23 '22 10:10

mgibsonbr


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
like image 5
Eser Aygün Avatar answered Oct 23 '22 12:10

Eser Aygün