[Tutor] Re: Can you modify every nth item in a list with a single
assignment?
Jeff Shannon
jeff@ccvcorp.com
Fri Jun 13 14:00:03 2003
Andrei wrote:
> >>> [ (item in range(0, len(b), 3) and [b[item]] or [2+b[item]])[0]
> for item in range(0, len(b))]
> [0, 3, 4, 3, 6, 7, 6, 9, 10]
>
> That's better.
Well, "better" being a matter of opinion. ;) This works, sure, but I'd
rather explicitly build a list of indices, and then explicitly loop
through that list and modify the primary list -- or else use that list
to exclude items from processing.
>>> indices = range(0,9,3)
>>> b = range(9)
>>> for n in range(len(b)):
... if n in indices:
... continue
... b[n] += 2
...
>>> b
[0, 3, 4, 3, 6, 7, 6, 9, 10]
>>>
This is more than one line of code, sure... but I can actually *read*
it! To quote 'import this', "Readability counts." As someone who
frequently maintains old code, I can guarantee you that I'd much rather
run across the explicit loops than the convoluted list comprehensions.
I can figure out the effect of the explicit loop in a matter of
seconds; the list comprehensions and the and/or tricks would take me *at
least* several minutes to painstakingly work out. This strikes me as a
very poor tradeoff.
Jeff Shannon
Technician/Programmer
Credit International