I have this code:
a=[['a','b','c'],['a','f','c'],['a','c','d']]
for x in a:
for y in x:
if 'a' in x:
x.replace('a','*')`
but the result is:
a=[['a','b','c'],['a','f','c'],['a','c','d']]
and bot a=[['b','c'],['f','c'],['c','d']]
What should I do so the changes will last?
If you want to remove all occurrences of 'a'
from all nested sublists, you could do:
>>> [[i for i in x if i != 'a'] for x in a]
[['b', 'c'], ['f', 'c'], ['c', 'd']]
if you want to replace them with asterisk:
>>> [[i if i != 'a' else '*' for i in x] for x in a]
[['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]
This isn't about the list. Python strings are immutable:
> a = 'x'
> a.replace('x', 'bye')
> a
'x'
You're replacing 'a' with '*' and then throwing away the result.
Try something like:
for i,value in enumerate(mylist):
mylist[i] = value.replace('x', 'y')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With