9

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

xzhu
  • 5,675
  • 4
  • 32
  • 52
  • 1
    for that particular example you can use foo[::2] also. – ChessMaster Feb 12 '12 at 07:34
  • foo[::2] is called "slice" in Python, look up that word to understand better ChessMaster's example. It works well in this particular case because the odd numbers coincidentally occupy odd positions in the list (even, for zero-based). – mgibsonbr Feb 12 '12 at 08:11
  • Run through the official tutorial (http://docs.python.org/tutorial/). It's pretty short and would have answered this question. – Steven Rumbalski Feb 12 '12 at 08:24

2 Answers2

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

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • What is this structure called? I need a name so that I can learn this in the documentation. – xzhu Feb 12 '12 at 06:59
  • @trVoldemort I was updating my answer (wanted to give a quick answer first, then elaborate...), there's more info now. – mgibsonbr Feb 12 '12 at 07:01
  • 2
    @nikow true. Personally, I don't like relying on 0 and non-zero for falsehood/truehood, preferring to be explicit about it. Been bitten many times in the past by errors related to this... (admittedly, not in Python, but in JavaScript, that has much more lousy semantics; but the scars remain) – mgibsonbr Feb 12 '12 at 08:54
  • @nikow For reference, Google's [Python style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=True/False_evaluations#True/False_evaluations) suggests using the implicit truth value, but [PEP 8](http://www.python.org/dev/peps/pep-0008/) doesn't seem to care. – Steven T. Snyder Mar 03 '12 at 00:21
5

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
Eser Aygün
  • 7,794
  • 1
  • 20
  • 30
  • What if I want `bar` to be `[1*2, 3*2, 5*2]`? Can I use lambda expression to map it? – xzhu Feb 12 '12 at 07:33
  • No, you need to use `map` function for that :) You can either combine `filter` and `map` as `map(lambda x: x * 2, filter(lambda x: x % 2 == 1, foo))` or use list comprehension as suggested by mgibsonbr. – Eser Aygün Feb 12 '12 at 07:37
  • Thank you! Is there a list for what lambda expressions can do? I think list comprehension is short and convenient, but not as universal as lambda. – xzhu Feb 12 '12 at 07:48
  • 1
    `map`, `reduce` and `filter` are three functions you can use for list manipulation. Here is a tutorial that explains all of them: http://www.bogotobogo.com/python/python_fncs_map_filter_reduce.html `lambda` notation is not specific to list manipulation operations. It is just a way of defining anonymous functions inside an expression. – Eser Aygün Feb 12 '12 at 07:57
  • @trVoldemort maybe [this question](http://stackoverflow.com/q/890128/520779) will help. IMHO the main advantage of `lambda` is allowing you to define very small functions in-place, so you don't have to declare them elsewhere before using them. For instance, to sort your list in descending order, you could use `foo.sort(lambda a,b: b-a)`. Without the lambda, you'd have to write a comparison function first and then pass it to `sort` (maybe never using that function elsewhere). – mgibsonbr Feb 12 '12 at 08:01