List comprehension confusion...
Manuel M. Garcia
mail at manuelmgarcia.com
Sat Feb 1 23:01:47 EST 2003
On Sun, 02 Feb 2003 03:10:27 GMT, Afanasiy <abelikov72 at hotmail.com>
wrote:
>I am confused about the purpose of list comprehensions.
>What can they do which an explicit for loop cannot?
I like that now we have a pretty compact notation for 2 dimensional
lists
list_2d = [ [0] * 3 for _ in range(5) ]
list_2d[3][1] = 7
assert list_2d == [ [0,0,0], [0,0,0], [0,0,0], [0,7,0], [0,0,0] ]
### THIS DOES NOT WORK! ###
list_2d = [ [0] * 3 ] * 5
list_2d[3][1] = 7
assert list_2d == [ [0,0,0], [0,0,0], [0,0,0], [0,7,0], [0,0,0] ]
also list comprehensions are slightly faster:
-----------------------
import time
t1 = time.clock()
out0 = []
for i in xrange(5000000):
if not (i % 3):
out0.append(i * 0.5)
print time.clock() - t1
t1 = time.clock()
out0 = [i * 0.5 for i in xrange(5000000) if not (i % 3)]
print time.clock() - t1
-----------------------
6.31521073209
5.78931763674
-----------------------
But this is hardly a reason to use them, even with such a large list,
the amount of time saved is so tiny.
I probably abuse them:
import operator
def normalize(list0):
t = reduce(operator.add, list0) * 1.0
return [ x / t for x in list0 ]
def normalize(list0):
t = 0.0
for x in list0:
t += x
out0 = []
for x in list0:
out0.append(x / t)
return out0
One is shorter, the other is easier to understand if you are not used
to functional programming constructs.
Manuel
More information about the Python-list
mailing list