0

I have a nested list and I am trying to replace a certain element of the list with something else.

  NL = [[1,2,3],
       [4,5,6],
       [7,8,9]];

Now, I need to update the list, let's say the user wants to change element at NL[1][1] (i.e. 5) to 'X'.

NL will be updated as

  NL = [[1,2,3],
       [4,'X',6],
       [7,8,9]];`

I am having trouble trying to find the position of the element and then changing it. Any help is much appreciated.

Thanks

  • Does this answer your question? [Finding the index of an element in nested lists in python](https://stackoverflow.com/questions/33938488/finding-the-index-of-an-element-in-nested-lists-in-python) – Asen Christov Jul 07 '20 at 11:10

7 Answers7

0

Use 2 indexes, 1 for the what nested list you want and one for what element of the nested list you want.

So in this case you want the 2nd list's 2nd element:

NL[1][1]='X'

Output:

[[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
0

Let's say you need to find the element 5 and want to replace it with 10. We iterate through the outer list and then each inner-list's elements. Once we find the element we look for, we can replace it by the indexes. We use enumerate to have the indexes once we find a matching element.

The following code replaces ALL matching elements (all occurences of 5).

NL = [[1,2,3], [4,5,6], [7,8,9]]

print(NL)  # prints: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for i, sublist in enumerate(NL):
    for y, element in enumerate(sublist):
        if element == 5:
            NL[i][y] = 10

print(NL)  # prints: [[1, 2, 3], [4, 10, 6], [7, 8, 9]]           
Cribber
  • 2,513
  • 2
  • 21
  • 60
0

Using numpy:

NL = np.array(NL)

mask = np.where(NL == 5)
NL[mask] = 10

array([[ 1,  2,  3],
       [ 4, 10,  6],
       [ 7,  8,  9]])

Solution2:

def get_index(num, List):
    for row, i in enumerate(List):
        if num in i:
            return row, i.index(num)
    return -1

idx = get_index(5,NL)
if idx>0:
    NL[idx[0]][idx[1]] = 7

[[1, 2, 3], [4, 7, 6], [7, 8, 9]]
Pygirl
  • 12,969
  • 5
  • 30
  • 43
  • Fancy solution! But I feel like importing an entire library is a bit overkill for something you can do in four lines without the import... – Cribber Jul 07 '20 at 10:46
  • Yeah but it's the most efficient solution. But for this task, a normal list method will do the job. – Pygirl Jul 07 '20 at 10:48
  • true, I guess it really depends on the length of their lists (and whether they use numpy anyway in other lines :) ) – Cribber Jul 07 '20 at 10:50
0

This will replace only the first occurrence of item_to_replace. If you want it to replace in all sublist then remove the break statement from try block.

item_to_replace = 5
for lst in NL:
    try:
        index = lst.index(item_to_replace)
        lst[index] = # your replacement for item_to_replace
        break
    except ValueError:
        continue
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
0

You should access to element by indexes. You have 2D list (array) so you should use 2 indexes: NL[1][1] = "X".

Complete code:

NL = [[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]]

print("Original: {}".format(NL))

NL[1][1] = "X"

print("New: {}".format(NL))

Output:

>>> python3 test.py
Original: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New: [[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
milanbalazs
  • 4,811
  • 4
  • 23
  • 45
0

just use NL[1][1] = 'X'

then print(NL)

Kevin Omar
  • 127
  • 9
0

I am having trouble trying to find the position of the element and then changing it.

Most of the answers here seem to have missed that part, and assumed you had the position.



You can use a nested list comprehension:

NL = [[1,2,3],
      [4,5,6],
      [7,8,9]]

NL = [['X' if i==5 else i for i in j] for j in NL]

print(NL)

Output:

[[1, 2, 3],
 [4,'X',6],
 [7, 8, 9]]
Red
  • 26,798
  • 7
  • 36
  • 58