list of the lists - append after search

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Thu Mar 2 14:56:51 EST 2017


Peter Otten <__peter__ at web.de> writes:

> Andrew Zyman wrote:
>
>> On Thursday, March 2, 2017 at 11:27:34 AM UTC-5, Peter Otten wrote:
>>> Andrew Zyman wrote:
>>> .....
>>> .....
>>> > End result:
>>> >  ll =[ [a,1], [b,2], [c,3], [blah, 1000, 'new value'] ]
>>> 
>>> >>> outer = [["a", 1], ["b", 2], ["c", 3], ["blah", 1000]]
>>> >>> for inner in outer:
>>> ...     if inner[0] == "blah":
>>> ...         inner.append("new value")
>> 
>> thank you. this will do.
>> Just curious, is the above loop can be done in a one-liner?
>
> Ah, that newbie obsession ;)
>
>>>> outer = [["a", 1], ["b", 2], ["c", 3], ["blah", 1000]]
>>>> [inner + ["new value"] if inner[0] == "blah" else inner for inner in 
> outer]
> [['a', 1], ['b', 2], ['c', 3], ['blah', 1000, 'new value']]
>
> Note that there is a technical difference to be aware of -- matching
> lists are replaced rather than modified.

I take it you are too sane, or too kind, to suggest the obvious
solution:

>>> outer = [["a", 1], ["b", 2], ["c", 3], ["blah", 1000]]
>>> [inner.append("new value") for inner in outer if inner[0] == "blah"]
[None]
>>> outer
[['a', 1], ['b', 2], ['c', 3], ['blah', 1000, 'new value']]

[snip]


More information about the Python-list mailing list