How to manipulate elements of a list in a single line of code?
mrstephengross
mrstevegross at gmail.com
Mon Feb 25 16:39:26 EST 2008
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
More information about the Python-list
mailing list