0

how do I change the value of 2d array without knowing its index?

Code:

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

for row in array:
    for col in row:
        if col == 2:
           ??????????? #this is what im looking for

2
  • please post a sample input and output Commented Jun 19, 2020 at 16:02
  • That's not a 2D array. Commented Jun 19, 2020 at 16:04

4 Answers 4

2

Try enumerate() in both for loops, which returns index position and value. Then change directly in your array.

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

for ir, row in enumerate(array):
    for ic, col in enumerate(row):
        if col == 2:
            array[ir][ic]= 99
Sign up to request clarification or add additional context in comments.

Comments

1

You could use enumerate function:

for row in array:
    for i,col in enumerate(row):
        if col == 2:  
            row[i]=3

Comments

1

Try doing:

for row in array:
    col[2] = #whatever you want to do

1 Comment

This will try replacing at index 2 not value 2.
1

here is with numpy 2d array

import numpy as np
array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
array2d = np.array(array)
array2d

Out[1]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

# Here case if you know or column and/or row

array2d[:,2] = 0   # here is you 'i'..for example set column 2 to 0
array2d

Out[2]:
array([[1, 2, 0],
       [4, 5, 0],
       [7, 8, 0]])

# Here case if you know condition, for example value '8' -> '88'

array2d[np.where(array2d ==8)] = 88
array2d

Out[3]:

array([[ 1,  2,  0],
       [ 4,  5,  0],
       [ 7, 88,  0]])

2 Comments

OP said he doesn't know the index ('i') to change the value.I believe he meant he want's to change when the value is a certain value, not change the whole column or row. But your answer made me doubt of that.
may be you right, so i extended my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.