M
mrstephengross
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 += '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
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 += '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