Changing python immutable type while iterating through mutable container like list

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

strings = ['a','b']

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

obviously this doesn't work in python, but the result I want to achieve is Strings = ['ac', 'bc']
What is the most pythonic way to achieve such a result?

Thanks for the great answers!

+3
source share
3 answers
strings = ['a', 'b']
strings = [s + 'c' for s in strings]
+6
source

You can use the list to create a list that has the following values: [s + 'c' for s in strings]. You can change the list in place as follows:

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

, . , , .

+3

.

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

Source: https://habr.com/ru/post/1775998/


All Articles