How to perform single line assignment for all list items in python

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 impossible to fulfill the assignment in a lambda function.

+4
source share
4 answers

I would not change my 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 job on the spot, but you mostly use the map for side effects and create a None list:

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 loop logic.

A simple loop is also more efficient:

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 

. .. , i.e map(str.strip, iterable), , , , .

+7

setitem() operator:

from operator import setitem

lol = [setitem(x, 1, -2) or x for x in lol]

lol :

from operator import setitem

map(lambda x: setitem(x, 1, -2), lol)

from operator import setitem

[setitem(x, 1, -2) for x in lol]

Padraic, .

+7

You tried:

>>> lol = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> lol =[[-2] + mas for x, *mas in lol]
>>> lol
[[-2, 2, 3], [-2, 5, 6], [-2, 8, 9]]
>>> 
+1
source

This answer is not the most efficient way, I just post it to get feedback on this. Quality and if it is a Pythonic way to do it, otherwise I will remove it if it is omitted, like this:

>>> lol
[[1, 3], [3, 4]]
>>> 
>>> 
>>> list(map(lambda x:x.__setitem__(1, -2), lol)) #list required in Python 3
[None, None]
>>> lol
[[1, -2], [3, -2]]
+1
source

All Articles