Replace elements in a list of lists python

python list replace element at index
python replace multiple items in list
python list replace
replace element in list python
python lists replace element
replace element in list of list python
find and replace items in list python
python change position of element in list

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?

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]

Python, Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list. Simply subset the list and assign new values to the subset. You can select single elements or you can change entire list slices at once. Use the IPython Shell to experiment with the commands below.

I'm going to use a simple example, but basically x is another variable and isn't linked to the list element. You have to change the list element directly in order to alter the list.

l=[1,2,3,4]
for x in l:
    x=x+1

This doesn't change the list

l=[1,2,3,4]
for i,x in enumerate(l):
    l[i]=x+1

this changes the list

Python, Given a list of lists, write a Python program to replace the values in the inner lists with their ordinal values. Examples: Input : [[1, 2, 3], [ 4, 5, 6], [ 7, 8, 9, 10]] Output  Python | Replace elements in second list with index of same element in first list Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list.

This is the case because you are only changing the temporary variable a. list = [1,2,3] for i in list: i+=1

list will still be [1,2,3]

you have to edit the string based on its index in the list

Python list: how can I replace certain items of the list?, Lists are mutable. So it is permitted and easy to change elements in a list. Let's make a list: lst = [ 'alpha', 'beta',  Replace Old Item With New in List Within Range Using Python You can change or update list element within full range or limited range. The full range may replace all the matching elements of the list. It may replace more than the one element of the list.

You can try using a dictionary object of python

import numpy as np
L = [['a','bob'],['a','bob'],['a','john']]
dic = {'bob':'b'} # you can specify more changes here
new_list = [dic.get(n, n) for n in np.concatenate(L)]
print(np.reshape(new_list,[-1,2]).tolist())

Result is

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

Iterate over large list of lists and replace its elements, Because of the large length of list_ and dictionary , the code that I currently have below takes almost 40min to run. I'm new to Python and I would  item itself is a copy too, but it is a copy of a reference to the original nested list, so when you refer to its elements the original list is updated. This isn't as convenient since you don't have the names; perhaps a dictionary or class would be a more convenient structure.

I might be a little to the party, but a more Pythonic way of doing this is using a map and a list comprehension. It can operate on a list of the list with any number of values.

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

[list(map(lambda x: x if x != 'bob' else 'b', i)) for i in l]

it gives you the desired output

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

The main idea is that the inner loop is iterating through the inner loop and using the simple lambda function to perform the replacement.

I hope that this helps anyone else who is looking out for something similar.

Replacing List Items, Replacing list items in Python, depending on the condition. Two options for solving to the list. # output of source and derived lists print(listOrigin) print(​listMask). or a list comprehension to create a new list: new_words = ['broccoli' if word == 'chicken' else word for word in words] any of which can be wrapped up in a function:

Python Lists and List Manipulation, The second row in this table index is how you access items in the list. # Define a list z = [3, 7, 4, 2]. Lists store an ordered collection of items  You can simply use list comprehension in python: def replace_element(YOUR_LIST, set_to=NEW_VALUE): return [i if SOME_CONDITION else NEW_VALUE for i in YOUR_LIST] for your case, where you want to replace all occurrences of 1 with 10, the code snippet will be like this:

11. Lists, We have already seen that we can assign list values to variables or pass lists as through the program changing all the loops; they will work correctly for any size list: Since strings are immutable, Python optimizes resources by making two  Iterate over large list of lists and replace its elements. an answer to Code Review Stack Exchange! of nested list over values in a Python dict. 6.

How to Modify Lists in Python, Modifying a list means to change a particular entry, add a new entry, or remove an existing Python can add elements to the list when you type List1.insert(0,  Replacing List Items There is a list of integers. Replace negative by -1, positive - by number 1, keep zero unchanged. 1st option - filling a new list depending on the values of the first one :

Comments
  • you are making a copy of things in list by for a in x, and not directly pointing to the element of x.
  • Side note: never shadow built-ins. Use list_ or L instead of list for your variable name.
  • @jpp or preferably something less generic that describes the contents... names or letter_and_name or something... :)
  • The "more pythonic" part isn't really a generic one considering the fact that bob can come anywhere in the sublist.
  • @Austin, Possibly. Given the example input, I'm happy to wait a little longer before making it more generic :)
  • @jpp don't forget poor "bobby" :)
  • Lol. If you think so, use if a == 'bob': instead of if 'bob' in a:.
  • or bobaganoush hahah