Question about 'for' loop

Steve Holden steve at holdenweb.com
Fri Aug 17 19:55:24 EDT 2007


Robert Dailey wrote:
> 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.
> 
That there is a "list comprehension".

> 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"]
> 
Who says you should? Beside you, that is. I am afraid the interpreter 
isn't psychic, and it doesn't have a DWIM [1] mode.

> However, instead I get an error message saying "TypeError: cannot 
> concatenate 'str' and 'list' objects"
> 
> How can I achieve the above? Thanks for reading.
> 
It's just a matter of understanding the syntax in a little more depth. 
In a week's time it will be blindingly obvious.

 >>> nicknames = ["bozo", "newbie", "newless cloob", "and welcome to 
c.l.py"]
 >>> [("hello " + name) for name in nicknames]
['hello bozo', 'hello newbie', 'hello newless cloob', 'hello and welcome 
to c.l.py']
 >>>

So, treat item [-1] from that list as the real sentiment of this message:

 >>> [("hello " + name) for name in nicknames][-1]
'hello and welcome to c.l.py'

regards
  Steve

[1]: Do What I Mean [and never mind what I say ...]
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list