[ACCEPTED]-Does python have a shorthand for this simple task?-python

Accepted answer
Score: 22
bar = [x for x in foo if x % 2 == 1]

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

  1. What you want to include in 18 the output list. Can be any expression involving 17 the variable(s) defined in the second part 16 (below). In this case, the element x, unmodified;

  2. A 15 variable, or expression, denoting an element 14 of the input list. Following the for keyword, each 13 element of the list will be bound to that 12 variable (if your list contains complex 11 objects, you can use destructuring assignment to refer only to specific 10 parts of it). In this case, each item of 9 the list is bound to x;

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

  4. A 6 condition that the element must meet to 5 be included in the result (optional). If 4 included, add the keyword if followed by an 3 expression to determine whether or not that 2 element will be included in the output list. In 1 this case, it will be if the number is odd.

Score: 5

filter function is what you are looking for:

bar = filter(lambda x: x % 2 == 1, foo)

The 1 expression lambda x: x % 2 == 1 is basically equivalent to

def isOdd(x):
    return x % 2 == 1

More Related questions