On Mon, Jan 18, 2010 at 8:07 AM, Kit <span dir="ltr"><<a href="mailto:wkfung.eric@gmail.com">wkfung.eric@gmail.com</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">

Hello Everyone, I am not sure if I have posted this question in a<br>
correct board. Can anyone please teach me:<br>
<br>
What is a list compression in Python?<br>
<br>
Would you mind give me some list compression examples?<br></blockquote><div><br></div><div>Do you mean list *comprehension*? If so, its a special syntax for list construct which can be used for shorter, clearer code (provided one doesn't abuse it, at which point it becomes quite obtuse). Its never required: nothing you do with a list comprehension you couldn't do with a standard loop.</div>

<div><br></div><div>For example:</div><div><br></div><div>evens = []</div><div>for n in range(100):</div><div>    if n %2 == 0:</div><div>        evens.append(n)</div><div><br></div><div>verses:</div><div><br></div><div>
my_list = [n for n in range(100) if n % 2 == 0]</div>
<div> </div><div>The basic syntax is:</div><div><br></div><div>[<expression that is appended> for <name> in <iterable>]</div><div><br></div><div>The 'if' part at the end is optional. The syntax is converted into a for loop that builds a list, and then returns it to you.</div>

<div><br></div><div>So, basically it becomes:</div><div><br></div><div>temp = []</div><div>for <name> in <iterable>:</div><div>    temp.append(<expression that is appended>)</div><div><br></div><div>Except the 'temp' variable doesn't really have  a name and is returned from the comprehension, where you can give it a name. Sometimes you need an 'if' clause, sometimes you don't. Sometimes your 'expression to be appended' is very simple, other times you mutate it. For example, an easy way to convert a list of numbers into a list of strings is:</div>

<div><br></div><div>[str(x) for x in range(10)]</div><div><br></div><div>HTH,</div><div><br></div></div><div name="mailplane_signature">--S</div>