Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change values in a list - python

Tags:

python

list

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?

like image 313
ariel Avatar asked Dec 29 '22 17:12

ariel


2 Answers

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']]
like image 114
SilentGhost Avatar answered Jan 09 '23 04:01

SilentGhost


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')
like image 24
Ken Avatar answered Jan 09 '23 04:01

Ken