# [Chicago] A list comprehension???

Julian Eden julianeden2 at gmail.com
Tue May 5 01:57:28 CEST 2015

```That's a slightly challenging first list comprehension problem.

List comprehensions are just a shorter syntax for creating lists.

Here are some examples. The last one is the solution to your problem.

Keep in mind that 'x' is an arbitrary variable name, you could use
anything. x is just a variable used within the list comprehension.

[ x for x in range(5) ]        ->    [0, 1, 2, 3, 4]
[ x for x in 'cat' ]      ->      [ 'c', 'a', 't' ]
[ 2 * x for x in range(3) ]     ->    [0, 2, 4]
[ x * x for x in range(4) ]      ->     [0, 1, 4, 9]
[ 5 for x in range(6) ]    ->       [5, 5, 5, 5, 5, 5]

[ x * (x + 1) for x in range(10) ]      ->    the one you asked about

On Mon, May 4, 2015 at 6:39 PM, Lewit, Douglas <d-lewit at neiu.edu> wrote:

> Hi there,
>
> I'm reading this book, "Data Structures & Algorithms in Python" by
> Goodrich, Tamassia, and Goldwasser.  A pretty good book, it really does
> into detail about the Python language with various examples.
>
> Anyhow, one of the exercises is as follows:
>
> Demonstrate how to use Python's list comprehension syntax to produce the
> list:
> [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].
>
> I'm struggling with this!
>
> The best I can do is the following:
>
> A = [0]
> i = 2
> while i <= 18:
>     A.append(A[-1] + i)
>      i+= 2
>
> print(A)
>
> Well it does work!  BUT it's not a list comprehension!
>
> Any suggestions?
>
> Thanks,
>
> Douglas.
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20150504/3ff1b46b/attachment.html>
```