Reputation: 1
I have done the following snippet, a list where I went line by line and replaced the dots with commas, however in the end the list remains the same since only the line variable changes. How to update the list with the replaced values?
for line in mylist:
line=line.replace('.',',')
line=line.replace('a','b')
I am looking for a quick pythonic solution, other than using a 2nd list to save the replaced value. I'd like to use only 1 list, if possible and "update" it on the go.
I have multiple operations inside the for
, for example in the way edited above, making the list update from the for is not possible as a "1 liner" like it's commonly done. I was looking for some sort of other way to update it if possible.
Upvotes: 2
Views: 63
Reputation: 96
Another one solution is to use str.translate, if replacements have always one character of length.
replace = lambda x: x.translate(str.maketrans('.a', ',b'))
mylist[:] = map(replace, mylist)
Upvotes: 0
Reputation: 15071
Something along this should work:
def do_stuff(elem):
return ...
for i in range(len(mylist)):
mylist[i] = do_stuff(mylist[i])
or
mylist[:] = [do_stuff(line) for line in mylist]
Upvotes: 0
Reputation: 10926
If you want to avoid creating a new list, do it like this:
for n, line in enumerate(mylist):
mylist[n] = line.replace('.',',')
You might prefer this if the list is very long. But if you're OK with creating a new list, Stephen Rauch's solution is more "Pythonic."
Upvotes: 0
Reputation: 49784
Try:
mylist[:] = [line.replace('.',',').replace('a','b') for line in mylist]
Upvotes: 2