Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a 'one-liner' assignment on all elements of a list of lists in python

Tags:

python

list

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.

like image 596
rwolst Avatar asked Dec 04 '22 01:12

rwolst


1 Answers

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.

like image 178
Padraic Cunningham Avatar answered Dec 22 '22 01:12

Padraic Cunningham