[Tutor] Fwd: syntax question

Moishy Gluck moishyyehuda at gmail.com
Wed May 21 18:00:40 CEST 2008


---------- Forwarded message ----------
From: Moishy Gluck <moishyyehuda at gmail.com>
Date: Wed, May 21, 2008 at 12:00 PM
Subject: Re: [Tutor] syntax question
To: Eric Abrahamsen <girzel at gmail.com>


You appear to be referring to list comprehension. Here is a link to list
comprehension is the python docs.

http://docs.python.org/tut/node7.html#SECTION007140000000000000000

[index for index in iterable]

Some examples would be:

colors = ["red", "green", "blue"]

hexValues = {"red": "ff0000", "green": "00ff00", "blue": "0000ff"}

#Get hexadecimal values of each color.
print [hexValues[color] for color in colors]

#Get a copy of the same list.
print [color for color in colors]

#Get the length of each member.
print [len(color) for color in colors]

#add optional if statment.
print [color for color in colors if len(color) > 3]

The output would be:

['ff0000', '00ff00', '0000ff']
['red', 'green', 'blue']
[3, 5, 4]
['green', 'blue']


On Wed, May 21, 2008 at 8:27 AM, Eric Abrahamsen <girzel at gmail.com> wrote:

> Hi all,
>
> This is a syntax that I've seen on occasion in other people's code:
>
> theme = (VALID_THEMES[0], theme) [ theme in VALID_THEMES ]
>
> I have no idea how this works, or how to go about looking it up. Can
> someone enlighten me as to what's happening here?
>
> Many thanks,
> Eric
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080521/e3bce0ad/attachment-0001.htm>


More information about the Tutor mailing list