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

Ben C spamspam at spam.eggs
Mon Feb 25 16:43:06 EST 2008


On 2008-02-25, mrstephengross <mrstevegross 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' ]

Yes, it's called a "list comprehension", and is many people's favourite
Python feature.

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

You can also add a condition

    list2 = [x + 'foo' for x in list1 if x != "bar"]

for example.



More information about the Python-list mailing list