list of the lists - append after search

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Thu Mar 2 15:31:27 EST 2017


Andrew Zyman writes:

> On Thursday, March 2, 2017 at 2:57:02 PM UTC-5, Jussi Piitulainen wrote:
>> 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]
>
> Arh!!! this is it :)
>
> I'm sure i'll regret this line of code in 2 weeks - after i
> successfully forget what i wanted to achieve :)

Jokes aside, you should strive to express your intention in your code.
Be kind to your future self. Write the three-line loop if you want
in-place modification.

I use comprehensions a lot, but not to save lines. I might make Peter's
expression above a four-liner to make its structure more visible:

  res = [ ( inner + ["new value"]
            if inner[0] == "blah"
            else inner )
          for inner in outer ]

Maybe.


More information about the Python-list mailing list