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

Dan thermostat at gmail.com
Mon Feb 25 16:42:20 EST 2008


On Feb 25, 4:39 pm, mrstephengross <mrstevegr... at gmail.com> wrote:
> I would like to translate the contents of a list. For instance, let's
> say I've got a list of strings and I want to append "foo" to each
> element. I might do the following;
>
>   list1 = ['a', 'b', 'c']
>   for i in range(0, len(list1)): list1[i] += 'foo'
>
> Ok, that much works. But what if I don't want to modify the contents
> of list1. Instead, I want list2 to hold the modified contents, like
> so:
>
> 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' ]
>
> Any ideas?
>
> Thanks,
> --Steve

You're so close.

>>> list2 = [ item+"foo" for item in list1 ]

-Dan



More information about the Python-list mailing list