0

I don't know if this question has been asked before, but it seems that I can't find the function that I am looking for. I want to add two different string to different strings in a list. Something like this:

old_list: ['spider','cat','iron','super','bat']

old_list: ['spiderman','catwoman','ironman','superwoman','batman'] 

So I want some kind of function that changes the strings by adding 'man' or 'woman' without making a new list. I think/know it can be done with some kind of for-loop but can't seem to find a easy way of doing it. And I am sorry if this question has been asked before, but I can't really find an answer to this specific function.

2 Answers 2

3

Slice-assign back into the list.

>>> ['{}{}'.format(pref, suff) for (pref, suff) in zip(old_list, itertools.cycle(('man', 'woman')))]
['spiderman', 'catwoman', 'ironman', 'superwoman', 'batman']
>>> id(old_list)
43518144
>>> old_list[:] = ['{}{}'.format(pref, suff) for (pref, suff) in zip(old_list, itertools.cycle(('man', 'woman')))]
>>> id(old_list)
43518144
>>> old_list
['spiderman', 'catwoman', 'ironman', 'superwoman', 'batman']
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer. Is there a more simple way of doing it? I am still new to python and it seems a bit complicated for me.
You could iterate over the indexes of the elements, but the jury is out on whether or not that is actually "simpler".
0

Just for the sake of a simpler answer, I will post this one:

for i in range(len(old_list)):
    old_list[i] += suffixes[i%len(suffixes)]

Note you can have any number of suffixes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.