list of the lists - append after search

Peter Otten __peter__ at web.de
Thu Mar 2 14:21:48 EST 2017


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.

>> While this is what you are asking for it will get slower as the list
>> grows. A better solution uses a dictionary:
> 
>> >>> lookup = {inner[0]: inner[1:] for inner in outer}
> 
> Yes, understood, i don't expect the list to grow above a few thousand
> entries. But i do agree that utilizing the dict is more efficient.




More information about the Python-list mailing list