[Tutor] changing list element in loop
Steven D'Aprano
steve at pearwood.info
Sat Apr 27 13:20:37 CEST 2013
Oh, and another thing...
On 27/04/13 20:31, Jim Mooney wrote:
>What's the simplest way to go through a list, find
> something, and replace it with something else?
The simplest way is not to do it at all. Instead, create a new list:
vowels = 'aeiouy'
result = []
for char in vowels:
if char == 'e':
char = 'P'
result.append(char)
result = ''.join(result)
print(result)
Of course, in this specific case, even faster and simpler is this:
result = vowels.replace('e', 'P')
but that's specifically a string method and doesn't generalise to
lists of arbitrary objects.
--
Steven
More information about the Tutor
mailing list