[Tutor] List comprehensions

Dinesh B Vadhia dineshbvadhia at hotmail.com
Wed Apr 9 22:15:32 CEST 2008


Sorry, let's start again.

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)

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

Hope this makes sense!  Thank-you.

Dinesh



----- Original Message ----- 
From: Kent Johnson 
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Sent: Wednesday, April 09, 2008 12:40 PM
Subject: Re: [Tutor] List comprehensions


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 = item + "\n"
> print result

I'm not sure what your goal is here. Do you mean to be accumulating all 
the values in data into result? Your sample code does not do that.

> I want to replace the for loop with a List Comrehension (or whatever) to 
> improve performance (as the data list will be >10,000].  At each stage 
> of the for loop I want to print the result ie.
>  
> [print (item + "\n")  for item in data]
>  
> But, this doesn't work as the inclusion of the print causes an invalid 
> syntax error.

You can't include a statement in a list comprehension. Anyway the time 
taken to print will swamp any advantage you get from the list comp.

If you just want to print the items, a simple loop will do it:

for item in data:
   print item + '\n'

Note this will double-space the output since print already adds a newline.

If you want to create a string with all the items with following 
newlines, the classic way to do this is to build a list and then join 
it. To do it with the print included, try

result = []
for item in data:
   newItem = item + '\n'
   print newItem
   result.append(newItem)
result = ''.join(result)

Kent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080409/58ac11f9/attachment.htm 


More information about the Tutor mailing list