Reputation: 2234
I have a list. this list has sublists. Each sublist contains a string. I want to apply .replace()
to these strings to change a letter.
mylist = [["aus"],["ausser"],["bei"],["mit"],["noch"],["seit"],["von"],["zu"]]
for sublist in mylist:
sublist = [stuff.replace("s", "Q") for stuff in sublist]
print(mylist)
But it just returns the original list. It should return
[["auQ"],["auQQer"],["bei"],["mit"],["noch"],["Qeit"],["von"],["zu"]]
Why doesn't my code change my subslists even though I redefine them within the for loop?
Upvotes: 2
Views: 1309
Reputation: 658
You Can use
mylist = [["aus"],["ausser"],["bei"],["mit"],["noch"],["seit"],["von"],["zu"]]
for i in range(0,len(mylist)):
mylist[i] = [stuff.replace("s", "Q") for stuff in mylist[i]]
print(mylist)
Upvotes: 0
Reputation: 920
An alternative that uses map
:
mylist = [["aus"],["ausser"],["bei"],["mit"],["noch"],["seit"],["von"],["zu"]]
secondList = list(map(lambda l: [l[0].replace('s', 'Q')], mylist)) # python 3
#secondList = map(lambda l: [l[0].replace('s', 'Q')], mylist) # python 2
>>> mylist
[['aus'], ['ausser'], ['bei'], ['mit'], ['noch'], ['seit'], ['von'], ['zu']]
>>> secondList
[['auQ'], ['auQQer'], ['bei'], ['mit'], ['noch'], ['Qeit'], ['von'], ['zu']]
Upvotes: 1
Reputation: 18633
You could just do this in a one liner:
[[s.replace("s", "Q")] for l in mylist for s in l]
[['auQ'], ['auQQer'], ['bei'], ['mit'], ['noch'], ['Qeit'], ['von'], ['zu']]
But the reason this is happening is because you're repeatedly creating a new variable sublist
instead of assigning to the existing sublist. If you want to use your method, try this:
for l in mylist:
l[0] = l[0].replace("s", "Q")
print(mylist)
[['auQ'], ['auQQer'], ['bei'], ['mit'], ['noch'], ['Qeit'], ['von'], ['zu']]
Here, the sublists are modified in place (instead of creating a new, modified sublist) which in turn modifies the original list.
Upvotes: 2
Reputation: 9257
Thanks to @Hamms 's comment:
the reason the original doesn't work is because when it assigns the new list to sublist, it's merely overwriting the reference to the sublist provided by thefor loop, not the sublist itself.
This method works because it's creating an entirely new list rather than trying to modify the original:
mylist = [["aus"],["ausser"],["bei"],["mit"],["noch"],["seit"],["von"],["zu"]]
final = [j.replace("s", "Q") for k in mylist for j in k]
print(final)
Output:
['auQ', 'auQQer', 'bei', 'mit', 'noch', 'Qeit', 'von', 'zu']
Or you can do this in order to have your desired output:
mylist = [["aus"],["ausser"],["bei"],["mit"],["noch"],["seit"],["von"],["zu"]]
final = [[j.replace("s", "Q")] for k in mylist for j in k]
print(final)
Output:
[['auQ'], ['auQQer'], ['bei'], ['mit'], ['noch'], ['Qeit'], ['von'], ['zu']]
Upvotes: 3