How to manipulate elements of a list in a single line of code?

D'Arcy J.M. Cain darcy at druid.net
Mon Feb 25 22:47:13 CET 2008


On Mon, 25 Feb 2008 13:39:26 -0800 (PST)
mrstephengross <mrstevegross at gmail.com> wrote:
> 1  list1 = ['a', 'b', 'c']
> 2  list2 = []
> 3  for item in list1: list2.append(item + 'foo')
> 
> Is there a way to express lines 2-3 sort-of ilke this:
> 
>   list2 = [ for item in list1: item + 'foo' ]

You almost have it.

  list2 = [item + 'foo' for item in list1]

-- 
D'Arcy J.M. Cain <darcy at druid.net>         |  Democracy is three wolves
http://www.druid.net/darcy/                |  and a sheep voting on
+1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.



More information about the Python-list mailing list