Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace elements in a list of lists python

I have a list of lists as follows:

     list=[]
     *some code to append elements to list*

     list=[['a','bob'],['a','bob'],['a','john']]

I want to go through this list and change all instances of 'bob to 'b' and leave others unchanged.

    for x in list:
       for a in x:
          if "bob" in a:
             a.replace("bob", 'b')

After printing out x it is still the same as list, but not as follows:

    list=[['a','b'],['a','b'],['a','john']]

Why is the change not being reflected in list?

like image 567
KRB Avatar asked Sep 24 '18 16:09

KRB


People also ask

How do you replace an item in a list with another list in Python?

You can replace items in a Python list using list indexing, a list comprehension, or a for loop. If you want to replace one value in a list, the indexing syntax is most appropriate. To replace multiple items in a list that meet a criterion, using a list comprehension is a good solution.

How do you replace multiple elements in a list in Python?

One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.

How do you replace a string in a list of a list in Python?

If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension.

How do I update a nested list in Python?

To add new values to the end of the nested list, use append() method. When you want to insert an item at a specific position in a nested list, use insert() method. You can merge one list into another by using extend() method.


1 Answers

Because str.replace doesn't work in-place, it returns a copy. As immutable objects, you need to assign the strings to elements in your list of lists.

You can assign directly to your list of lists if you extract indexing integers via enumerate:

L = [['a','bob'],['a','bob'],['a','john']]

for i, x in enumerate(L):
    for j, a in enumerate(x):
        if 'bob' in a:
            L[i][j] = a.replace('bob', 'b')

Result:

[['a', 'b'], ['a', 'b'], ['a', 'john']]

More Pythonic would be to use a list comprehension to create a new list. For example, if only the second of two values contains names which need checking:

L = [[i, j if j != 'bob' else 'b'] for i, j in L]
like image 129
jpp Avatar answered Sep 19 '22 18:09

jpp