idiom for list looping

superpollo user at example.net
Wed Jul 29 13:02:14 CEST 2009


MRAB wrote:
> Xavier Ho wrote:
> 
>>     superpollo wrote:
>>
>>
>>         for (i, e) in enumerate(nomi):
>>            print i, "-", e
>>
>> Just to be random:
>>
>> print '\n'.join(["%s - %s" % (i, e) for i, e in enumerate(nomi)])
>>
>> This has one advantage: only print once. So it's slightly faster if 
>> you have a list of a large amount.
>>
> Slightly shorter:
> 
> print '\n'.join("%s - %s" % p for p in enumerate(nomi))
> 
> :-)

 >>> print '\n'.join("%s - %s" % p for p in enumerate(nomi))
   File "<stdin>", line 1
     print '\n'.join("%s - %s" % p for p in enumerate(nomi))
                                     ^
SyntaxError: invalid syntax
 >>> print '\n'.join(["%s - %s" % p for p in enumerate(nomi)])
0 - one
1 - two
2 - three
 >>> help()

Welcome to Python 2.3!  This is the online help utility.
...
 >>>

;-)

bye



More information about the Python-list mailing list