You'll have to wrap the map around a filter around the list:
example_map = map(lambda x: x*2, filter(lambda x: x*2/6. != 1, range(5)))
Answer from jwodder on Stack OverflowYou'll have to wrap the map around a filter around the list:
example_map = map(lambda x: x*2, filter(lambda x: x*2/6. != 1, range(5)))
Alternatively, you could filter your map rather than maping your filter.
example_map = filter(lambda x: x/6. != 1, map(lambda x: x*2, range(5)))
Just remember that you're now filtering the RESULT rather than the original (i.e. lambda x: x/6. != 1 instead of lambda x: x*2/6. != 1 since x is already doubled from the map)
Heck if you really want, you could kind of throw it all together with a conditional expression
example_map = map(lambda x: x*2 if x*2/6. != 1 else None, range(5))
But it'll leave you with [0, 2, 4, None, 8]. filter(None, example_map) will drop the Nones and leave you [0, 2, 4, 8] as expected.
python - using a conditional and lambda in map - Stack Overflow
Is there a way to perform "if" in python's lambda? - Stack Overflow
dictionary - Python - How to use map function and lambda function with if condition - Stack Overflow
pandas - Map an if statement in Python - Stack Overflow
Videos
>>> lst = [1,2,4,5]
>>> map(lambda x: 'lower' if x < 3 else 'higher', lst)
['lower', 'lower', 'higher', 'higher']
Aside: It's usually preferred to use a list comprehension for this
>>> ['lower' if x < 3 else 'higher' for x in lst]
['lower', 'lower', 'higher', 'higher']
Ternary operator:
map(lambda x: 'lower' if x<3 else 'higher', lst)
The syntax you're looking for:
lambda x: True if x % 2 == 0 else False
But you can't use print or raise in a lambda.
why don't you just define a function?
def f(x):
if x == 2:
print(x)
else:
raise ValueError
there really is no justification to use lambda in this case.
map always produces one output item for each input item, it can not remove elements. Furthermore, map should not be used to mutate objects, that's not its job, and because it's lazy the results can be unexpected.
filter is designed to create an output with less elements than the input, although it's mostly useful if you already have a ready-made predicate (filtering) function.
Since you do not, you can and should use comprehensions which provide a relatively terse way to perform iteration, filtering, mapping and collection in a single construct:
Copywordlist = ['hello','world','Tom']
checklist = ['hello','world']
print('before')
print(wordlist)
wordlist = [word for word in wordlist if word not in checklist]
print('after')
print(wordlist)
ps: if you want to modify things in-place, use a regular loop
You can try this instead, which doesn't use lambda but accomplishes your goal. Let us know if you absolutely must use lambda. The issue with your lambda expression is that your modifying the list that you are providing to map in the lambda function.
Copywordlist_2 [word for word in wordlist if word not in checklist and word]
The last and word is to not add None to your list.
Try
lambda x: 1 if x == "C" else 0
possible duplicate of Is there a way to perform "if" in python's lambda
Example :
map(lambda x: True if x % 2 == 0 else False, range(1, 11))
result will be - [False, True, False, True, False, True, False, True, False, True]
It will be simpler to just do this:
df["Cherbourg"] = (df["Embarked"] == "C").astype('int)
because the lambda function needs to be created len(data) times, thus inefficient.
Not true, in the example the lambda definition is evaluated only once at compile time and not len(data) times - there is no need to assign it to a name for performance reasons. Look at Sergey's answer, he proves lambda is not expensive at all for this case.
If you do want to give it a name for the sake of clarity, you should just use a def statement instead. Assigning a lambda to a name is considered bad style: according to PEP-8 Programming Recommendations you should "Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier". Quoting from the official style guide:
Yes:
def f(x): return 2*x
No:
f = lambda x: 2*x:
The only difference between lambda and the one-line def is that def will give it a name (probably an extra LOAD_CONST):
>>> import dis
>>> def _(x):
return f(x, 30)
>>> dis.dis(_)
2 0 LOAD_GLOBAL 0 (f)
2 LOAD_FAST 0 (x)
4 LOAD_CONST 1 (30)
6 CALL_FUNCTION 2
8 RETURN_VALUE
>>> dis.dis(lambda x: f(x, 30))
1 0 LOAD_GLOBAL 0 (f)
2 LOAD_FAST 0 (x)
4 LOAD_CONST 1 (30)
6 CALL_FUNCTION 2
8 RETURN_VALUE
As you can see above, both forms compile to the same bytecode.
The lisp inspired functions map, filter and reduce always felt a bit alien in Python. Since the introduction of list comprehensions (at version 2.0 IINM) they became the idiomatic way to achieve the same result. So this:
new_data = map(lambda x: f(x, 30), data)
Is often written as:
new_data = [f(x, 30) for x in data]
If data is big and you are just iterating over it, generator expressions trade memory for cpu:
for value in (f(x, 30) for x in data):
do_something_with(value)
The lispy constructs like map, filter and reduce are likely to be retired (moved to the functools module) and I recommend the use of list comprehensions and generator expressions in new code.
Last, Python is surprisingly counterintuitive regarding performance. You should always profile in order to put your beliefs about performance in check.
Bottom line: never worry about "optimizing" a damn thing until you have profiled it and know for sure it's a relevant bottleneck.
Lambda creates only once when map calls
In [20]: l = list(range(100000))
In [21]: %timeit list(map(lambda x: x * 2, l))
100 loops, best of 3: 13.8 ms per loop
In [22]: g = lambda x: x * 2
In [23]: %timeit list(map(g, l))
100 loops, best of 3: 13.8 ms per loop
As you can see, the execution time is not changed.
pass is a statement, but inline if, being an operator, needs its operands to be expressions. map can’t actually remove elements from the sequence, but filter (returns a new list with only the values for which the function returns True) can:
print filter(lambda x: str(x)[-1] == '2', even)
If you're like me and don't like filters and lambda, you can accomplish this with Python list comprehension:
print [x for x in even if str(x)[-1] == '2']
This is an XY problem. You're using a map when it asks for a list comprehension. It's essentially asking for a filter, not a map.
>>> [x1+x2 for x1, x2 in zip(L1, L2) if x1>10 and x2<5]
[18, 57, 103]
You could do it in a functional style, but it's so ugly. Don't do this.
L3 = list(map(
lambda t: t[0]+t[1],
filter(
lambda t: t[0]>10 and t[1]<5,
zip(L1, L2)
)
))
print(L3) # -> [18, 57, 103]
Have a look here: The lambda function must have a return value and if your if statement is not true, there is none. Therefore, you would have to add an else statement, for example:
L4 = map(lambda x: x[0] + x[1] if (x[0] > 10 and x[1] < 5) else 0, zip(L1,L2))
Results in
[0, 0, 0, 18, 0, 0, 57, 0, 103]
Your first try (L3) does not work because lambda can no longer unpack tuples in python 3.x (see: here)
Please also note that map() returns an object and in order to print its content you would have to call
print(list(map_object))
# in your case:
print(list(L4))
# or set()
Edit based on comment: if you really want a one-liner and as your first sentence says "using zip and list comprehension" and you want to leave out 0s, then this might work and is easier than map and lambda:
L3 = [x[0]+x[1] for x in zip(L1,L2) if (x[0] > 10 and x[1] < 5)]
Edit 2 if you really, really, really insist on using map and lambda:
L4 = map(lambda x: x[0] + x[1], filter(lambda x: (x[0] > 10 and x[1] < 5), zip(L1,L2)))