4

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?

2
  • Also, your code is wrong. You wouldn't get any result at all, because it raises AttributeError Commented May 12, 2010 at 17:50
  • What are you trying to accomplish? Commented May 12, 2010 at 17:53

6 Answers 6

5

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']]
Sign up to request clarification or add additional context in comments.

Comments

4

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')

Comments

1

You really want to replace the element in the nested list, like so:

a=[['a','b','c'],['a','f','c'],['a','c','d']]    
for row in a:
   for ix, char in enumerate(row):
       if char == 'a':
           row[ix] = '*'

With the result:

a = [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]

Comments

0
a=[['a','b','c'],['a','f','c'],['a','c','d']]
b=[[subelt.replace('a','*') for subelt in elt] for elt in a]
print(b)

# [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]

Comments

0

This would work:

a=[['a','b','c'],['a','f','c'],['a','c','d']]
for x in a:    
    for y in x:    
        if y == 'a':
            x.remove(y)

Or even simpler:

y = 'a'
a=[['a','b','c'],['a','f','c'],['a','c','d']]
for x in a:    
    x.remove(y)

Which gives you a=[['b','c'],['f','c'],['c','d']].

Note: See the documentation on remove() for lists here.

Comments

0

Search for the function replace:

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

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.