Extracting elements over multiple lists?

Terry Reedy tjreedy at udel.edu
Mon Nov 7 19:06:53 EST 2011


On 11/7/2011 1:22 PM, John Gordon wrote:
> In<cf007146-3a08-44c4-bf01-d1a9253c83e3 at o19g2000vbk.googlegroups.com>  JoeM<josephmeiring at gmail.com>  writes:
>
>> Thanks guys, I was just looking for a one line solution instead of a
>> for loop if possible. Why do you consider
>
>> [x.remove(x[0]) for x in [a,b,c]]
>
>> cheating? It seems compact and elegant enough for me.

It looks like incomplete code with 'somelists = ' or other context 
omitted. It saves no keypresses '[',...,SPACE,...,']' versus 
...,':',ENTER,TAB,... . (TAB with a decent Python aware editor.)

> I wouldn't call it cheating, but that solution does a fair bit of
> unneccessary work (creating a list comprehension that is never used.)

The comprehension ( the code) is used, but the result is not. If the 
source iterator has a large number of items rather than 3, the throwaway 
list could become an issue. Example.

fin = open('source.txt')
fout= open('dest.txt, 'w')
for line in fin:
   fout.write(line.strip())
# versus
[fout.write(line.strip()) for line in fin]

If source.txt has 100 millions lines, the 'clever' code looks less 
clever ;=). Comprehensions are intended for creating collections (that 
one actually wants) and for normal Python coding are best used for that.

-- 
Terry Jan Reedy




More information about the Python-list mailing list