Given a list of lists lol
, I would like to do in one line
for ele in lol:
ele[1] = -2
I tried
lol = map(lambda x: x[1] = -2, lol)
But its not possible to perform an assignment in a lambda function.
I would not change your own approach but to answer your question:
lol = [[1,3],[3,4]]
from operator import setitem
map(lambda x: setitem(x, 1, -2), lol)
print(lol)
[[1, -2], [3, -2]]
It does the assignment in place but you are basically using map for side effects and creating a list of None's:
In [1]: lol = [[1, 3], [3, 4]]
In [2]: from operator import setitem
In [3]: map(lambda x: setitem(x, 1, -2), lol)
Out[3]: [None, None]
In [4]: lol
Out[4]: [[1, -2], [3, -2]]
So really stick to your own for loop logic.
They simple loop is also the more performant:
In [13]: %%timeit
lol = [[1,2,3,4,5,6,7,8] for _ in range(100000)]
map(lambda x: setitem(x, 1, -2), lol)
....:
10 loops, best of 3: 45.4 ms per loop
In [14]:
In [14]: %%timeit
lol = [[1,2,3,4,5,6,7,8] for _ in range(100000)]
for sub in lol:
sub[1] = -2
....:
10 loops, best of 3: 31.7 ms per
The only time map. filter etc.. really do well is if you can call them with a builtin function or method i.e map(str.strip, iterable)
, once you include a lambda the performance will usually take a big hit.
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