[Tutor] Use of List Comprehension?
Bob Gailer
bgailer at alum.rpi.edu
Thu Jul 29 06:23:46 CEST 2004
At 09:46 PM 7/28/2004, Hee-Seng Kye wrote:
>I was wondering under which circumstances one might use list
>comprehension. Does it have any effect on computation time, or is it used
>for a matter of simplicity (though could be less easier to read)?
For me list comprehension is a shorthand (idiomatic) replacement for a list
initialization followed by one (or more nested) for loop(s), append calls
and if statements. A lot can be said in terse code. It is easier to write
and read. Computation time is probably faster.
Compare:
l = []
for x in y:
if x > 3:
l.append(x)
with:
l = [x for x in y if x > 3]
Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell
More information about the Tutor
mailing list