[Tutor] List comprehensions

Kent Johnson kent37 at tds.net
Wed Apr 9 21:40:36 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 = 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


More information about the Tutor mailing list