Ben
Ben

Reputation: 158

Changing python immutable type while iterating through a mutable container such as list

I am wondering what is the most pythonic way to do the following and have it work:

strings = ['a','b']

for s in strings:  
    s = s+'c'

obviously this doesn't work in python but the result that I want to acheive is
strings = ['ac','bc']
Whats the most pythonic way to achieve this kind of result?

Thanks for the great answers!

Upvotes: 3

Views: 828

Answers (3)

Marek Sapota
Marek Sapota

Reputation: 20601

You can use map function for that.

strings = ['a', 'b']
strings = map(lambda s: s + 'c', strings)

Upvotes: 1

user395760
user395760

Reputation:

You can use list comprehension to create a list that has these values: [s + 'c' for s in strings]. You can modify the list in-place like this:

for i, s in enumerate(strings):
    strings[i] = s + 'c'

But I found that quite often, in-place modification is not needed. Look at your code to see if this applies.

Upvotes: 3

John Y
John Y

Reputation: 14529

strings = ['a', 'b']
strings = [s + 'c' for s in strings]

Upvotes: 6

Related Questions