Question about 'for' loop

Robert Dailey rcdailey at gmail.com
Fri Aug 17 18:45:54 EDT 2007


Hi,

I noticed that the 'for' loop can be used inline with a list definition. For
example:

print [i for i in mylist]

My first question is what is the name for this? I couldn't find this usage
in the python docs; I only managed to learn about it through code samples on
the internet.

Secondly, I'm wondering how I can use this method of a for loop to append
strings to strings in a list. For example:

mylist = [
"Hello ",
"Hello again "
]

I should be able to do this:

print [ i + "World" for i in mylist ]

Which should yield the output:

["Hello World", "Hello again world"]

However, instead I get an error message saying "TypeError: cannot
concatenate 'str' and 'list' objects"

How can I achieve the above? Thanks for reading.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070817/2031bc2d/attachment.html>


More information about the Python-list mailing list