[Tutor] List comprehensions

Kent Johnson kent37 at tds.net
Wed Apr 9 22:48:28 CEST 2008

Dinesh B Vadhia wrote:
> Here is a for loop operating on a list of string items:
> data = ["string 1", "string 2", "string 3", "string 4", "string 5", 
> "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"]
> result = ""
> for item in data:
>     result = <some operation on> item
>     print result
> I want to replace the for loop with another structure to improve 
> performance (as the data list will contain >10,000 string items].  At 
> each iteration of the for loop the result is printed (in fact, the 
> result is sent from the server to a browser one result line at a time)

Any savings you have from optimizing this loop will be completely 
swamped by the network time. Why do you think this is a bottleneck?

You could use
[ sys.stdout.write(some operation on item) for item in data ]

but I consider this bad style and I seriously doubt you will see any 
difference in performance.

> The for loop will be called continuously and this is another reason to 
> look for a potentially better structure preferably a built-in.

What do you mean 'called continuously'?


More information about the Tutor mailing list