Change one list item in place
Steve Holden
steve at holdenweb.com
Tue Nov 30 22:52:14 EST 2010
On 11/30/2010 8:28 PM, MRAB wrote:
> On 01/12/2010 01:08, Gnarlodious wrote:
>> This works for me:
>>
>> def sendList():
>> return ["item0", "item1"]
>>
>> def query():
>> l=sendList()
>> return ["Formatting only {0} into a string".format(l[0]), l[1]]
>>
>> query()
>>
>>
>> However, is there a way to bypass the
>>
>> l=sendList()
>>
>> and change one list item in-place? Possibly a list comprehension
>> operating on a numbered item?
>>
> There's this:
>
> return ["Formatting only {0} into a string".format(x) if i == 0 else
> x for i, x in enumerate(sendList())]
>
> but that's too clever for its own good. Keep it simple. :-)
I quite agree. That solution is so clever it would be asking for a fight
walking into a bar in Glasgow.
However, an unpacking assignment can make everything much more
comprehensible [pun intended] by removing the index operations. The
canonical solution would be something like:
def query():
x, y = sendList()
return ["Formatting only {0} into a string".format(x), y]
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon 2011 Atlanta March 9-17 http://us.pycon.org/
See Python Video! http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list