An array and nested list version:

In [163]: A=np.arange(12).reshape(3,4)
In [164]: Al = A.tolist()

For sliced indexing, a list comprehension (or mapping equivalent) works fine:

In [165]: A[:,1:3]
Out[165]: 
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])
In [166]: [l[1:3] for l in Al]
Out[166]: [[1, 2], [5, 6], [9, 10]]

For advanced indexing, the list requires a further level of iteration:

In [167]: A[:,[0,2,3]]
Out[167]: 
array([[ 0,  2,  3],
       [ 4,  6,  7],
       [ 8, 10, 11]])

In [169]: [[l[i] for i in [0,2,3]] for l in Al]
Out[169]: [[0, 2, 3], [4, 6, 7], [8, 10, 11]]

Again there are various mapping alternatives.

In [171]: [operator.itemgetter(0,2,3)(l) for l in Al]
Out[171]: [(0, 2, 3), (4, 6, 7), (8, 10, 11)]

itemgetter uses tuple(obj[i] for i in items) to generate those tuples.

Curiously, itemgetter returns tuples for the list index, and lists for slices:

In [176]: [operator.itemgetter(slice(1,3))(l) for l in Al]
Out[176]: [[1, 2], [5, 6], [9, 10]]
Answer from hpaulj on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-using-2d-arrays-lists-the-right-way
Using 2D arrays/lists in Python - GeeksforGeeks
Python creates only one inner list and one 0 object, not separate copies. This shared reference behavior is known as shallow copying (aliasing). If we assign the 0th index to another integer say 1, then a new integer object is created with the value of 1 and then the 0th index now points to this new int object as shown below · Similarly, when we create a 2d array as "arr = [[0]*cols]*rows" we are essentially extending the above analogy.
Published   December 20, 2025
🌐
Snakify
snakify.org › two-dimensional lists (arrays)
Two-dimensional lists (arrays) - Learn Python 3 - Snakify
In this array there are n = 5 rows, m = 6 columns, and the element with row index i and column index j is calculated by the formula a[i][j] = i * j.
🌐
Beauty and Joy of Computing
bjc.edc.org › Jan2017 › bjc-r › cur › programming › old-labs › python › 2D_lists.html
2D Lists in Python
The first index returns the internal list, and the second index then looks into that retrieved list. All of the previously mentioned list functions still operate on 2D lists: >>> cart[0][2] = "cabbage" >>> cart [ ["kale", "spinach", "cabbage"], ["olives", "tomatoes", "avocado"]] Now that you have some experience with lists in Python, try writing a function that takes a list of lists (2D) and returns all the items of each list concatenated together into one new list as shown below:
🌐
Carnegie Mellon University
cs.cmu.edu › ~15110-s22 › slides › week4-3-lists.pdf pdf
Lists and Methods 15-110 – Friday 02/11
When you loop over a 2D list and want to access every element, you need to use nested for loops. Often, the outer loop iterates over the indexes of the outer list (rows) and the inner loop iterates over ... This tells Python to call the built-in string function isdigit on the string s.
🌐
Processing
py.processing.org › tutorials › 2dlists
Two-Dimensional Lists \ Tutorials
Python Mode for Processing extends the Processing Development Environment with the Python programming language.
🌐
Reddit
reddit.com › r/learnpython › help finding the index of a given value within a 2d array
r/learnpython on Reddit: Help finding the index of a given value within a 2D array
November 13, 2022 -

Been messing around with numpy, trying to familiarize myself with it and seeing how I'd be able to utilize its arrays to store (very simple) map data for this text adventure game I've been working on. So far it seems like it'd be pretty darn useful, but I seem to have run into something of an issue.

My code is as follows (note: this is purposefully made with out a main class, because I am just trying to get the basic functionality down in my head before I incorporate it into my main program, and this is just easier for me):

# import numpy module as np
import numpy as np

# Establish the game map, a 3x3 grid of 0's
mainarray = np.array([[0, 0, 0],
                      [0, 0, 0],
                      [0, 0, 0]])

# Give feedback to make console easier to read
print(mainarray)
print("")
print("Placing player in center...")

# Place player on map (represented by a value of 1)
mainarray[1, 1] = 1

print(mainarray)

print("")
print("Locating player...")

# Attempt to find what the current index is of the value 1
print("")
print("Player is at index: ", np.where(mainarray == 1)[0][0])

In my head, I would like to eventually use this np.where() function (if I can) in one of the functions that moves my character. What I want to do is grab the current index of the "player" (represented by the number 1) and attempt to change that value to a 0, and change the value at an adjacent index to 1 (the tile that the player is moving to). Basically, I would like to use each index of the array as a sort of coordinate that I can take and use to move this "1" around the array, setting each index back to "0" after moving the "1", all based off user input.

Anyways, I am not getting any errors, however, the result that gets printed to the console is:

Player is at index:  1

Why is it just one number? It remains the same, even when I remove that second [0] in the last line. I don't fully understand how this function works, as this is the first time I've tried to use it, but since there are no errors, I have no clue what is going on.

Shouldn't I be receiving an index with two values, one for the column and one for the row? If not, how can I grab that as a result and use it in the way I described above? Is it even possible, or am I barking up the wrong tree with this function?

🌐
GeeksforGeeks
geeksforgeeks.org › python-using-2d-arrays-lists-the-right-way
Python | Using 2D arrays/lists the right way - GeeksforGeeks
This peculiar functioning is because Python uses shallow lists which we will try to understand. In method 1a, Python doesn't create 5 integer objects but creates only one integer object, and all the indices of the array arr point to the same int object as shown. If we assign the 0th index to another integer say 1, then a new integer object is created with the value of 1 and then the 0th index now points to this new int object as shown below · Similarly, when we create a 2d array as "arr = [[0]*cols]*rows" we are essentially extending the above analogy.
Published   June 20, 2024
Find elsewhere
🌐
Dot Net Perls
dotnetperls.com › 2d-python
Python - 2D List Examples - Dot Net Perls
Detail The multiplication of the coordinates returns a single integer for a 2D point. Here We define get_element and set_element methods. We compute indexes based on an "x" and "y" coordinate pair. def get_element(elements, x, y): return elements[x + (y * 4)] def set_element(elements, x, y, value): elements[x + (y * 4)] = value # Create a list of 16 elements.
🌐
Codecademy
codecademy.com › learn › introduction-to-python-for-finance › modules › learn-python3-lists › cheatsheet
Introduction to Python: Lists Cheatsheet | Codecademy
In order to access elements in a 2D list, an index for the sublist and the index for the element of the sublist both need to be provided. The format for this is list[sublist_index][element_in_sublist_index]. ... The .remove() method in Python ...
🌐
Guru99
guru99.com › home › python › python 2d arrays: two-dimensional list examples
Python 2D Arrays: Two-Dimensional List Examples
August 12, 2024 - Python Escape Character Sequences (Examples) Here we are going to insert values into two dimensional array using insert() function · Syntax: array.insert(index,[values]) where, the array is the input array · the index is the row position to insert a particular row · value are the values to be inserted into the array · Example: Insert to values in the array · #Create 2D array with 4 rows and 5 columns array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]] #insert the row at 5 th position array.insert(2, [1,2,3,4,5]) #insert the row at 6 th position array.insert(2, [1,2
🌐
Quora
quora.com › How-do-you-access-a-two-dimensional-list-in-Python
How to access a two-dimensional list in Python - Quora
Answer (1 of 2): You use []s for indexing twice: That said, if you really want a matrix, i.e., a 2-D array, you should use NumPy: Lists are containers, whereas NumPy arrays are mathematical objects.
🌐
NumPy
numpy.org › devdocs › user › basics.indexing.html
Indexing on ndarrays — NumPy v2.5.dev0 Manual
ndarrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection.
🌐
TutorialsPoint
tutorialspoint.com › home › python_data_structure › python 2d array
Understanding Python 2D Arrays
February 21, 2009 - In the below example a new data element is inserted at index position 2.
🌐
Krivers
krivers.net › 15112-s19 › notes › notes-2d-lists.html
2D Lists - 15-112: Fundamentals of Programming
Each of those lists would have three values representing the value in that row corresponding to a specific column. If you use your four row lists as items in an outer list, your grid is now represented as a 2D list. This lets you access each cell by first indexing into its row, and then its column!
Top answer
1 of 5
60

Selections or assignments with np.ix_ using indexing or boolean arrays/masks

1. With indexing-arrays

A. Selection

We can use np.ix_ to get a tuple of indexing arrays that are broadcastable against each other to result in a higher-dimensional combinations of indices. So, when that tuple is used for indexing into the input array, would give us the same higher-dimensional array. Hence, to make a selection based on two 1D indexing arrays, it would be -

x_indexed = x[np.ix_(row_indices,col_indices)]

B. Assignment

We can use the same notation for assigning scalar or a broadcastable array into those indexed positions. Hence, the following works for assignments -

x[np.ix_(row_indices,col_indices)] = # scalar or broadcastable array

2. With masks

We can also use boolean arrays/masks with np.ix_, similar to how indexing arrays are used. This can be used again to select a block off the input array and also for assignments into it.

A. Selection

Thus, with row_mask and col_mask boolean arrays as the masks for row and column selections respectively, we can use the following for selections -

x[np.ix_(row_mask,col_mask)]

B. Assignment

And the following works for assignments -

x[np.ix_(row_mask,col_mask)] = # scalar or broadcastable array

Sample Runs

1. Using np.ix_ with indexing-arrays

Input array and indexing arrays -

In [221]: x
Out[221]: 
array([[17, 39, 88, 14, 73, 58, 17, 78],
       [88, 92, 46, 67, 44, 81, 17, 67],
       [31, 70, 47, 90, 52, 15, 24, 22],
       [19, 59, 98, 19, 52, 95, 88, 65],
       [85, 76, 56, 72, 43, 79, 53, 37],
       [74, 46, 95, 27, 81, 97, 93, 69],
       [49, 46, 12, 83, 15, 63, 20, 79]])

In [222]: row_indices
Out[222]: [4, 2, 5, 4, 1]

In [223]: col_indices
Out[223]: [1, 2]

Tuple of indexing arrays with np.ix_ -

In [224]: np.ix_(row_indices,col_indices) # Broadcasting of indices
Out[224]: 
(array([[4],
        [2],
        [5],
        [4],
        [1]]), array([[1, 2]]))

Make selections -

In [225]: x[np.ix_(row_indices,col_indices)]
Out[225]: 
array([[76, 56],
       [70, 47],
       [46, 95],
       [76, 56],
       [92, 46]])

As suggested by OP, this is in effect same as performing old-school broadcasting with a 2D array version of row_indices that has its elements/indices sent to axis=0 and thus creating a singleton dimension at axis=1 and thus allowing broadcasting with col_indices. Thus, we would have an alternative solution like so -

In [227]: x[np.asarray(row_indices)[:,None],col_indices]
Out[227]: 
array([[76, 56],
       [70, 47],
       [46, 95],
       [76, 56],
       [92, 46]])

As discussed earlier, for the assignments, we simply do so.

Row, col indexing arrays -

In [36]: row_indices = [1, 4]

In [37]: col_indices = [1, 3]

Make assignments with scalar -

In [38]: x[np.ix_(row_indices,col_indices)] = -1

In [39]: x
Out[39]: 
array([[17, 39, 88, 14, 73, 58, 17, 78],
       [88, -1, 46, -1, 44, 81, 17, 67],
       [31, 70, 47, 90, 52, 15, 24, 22],
       [19, 59, 98, 19, 52, 95, 88, 65],
       [85, -1, 56, -1, 43, 79, 53, 37],
       [74, 46, 95, 27, 81, 97, 93, 69],
       [49, 46, 12, 83, 15, 63, 20, 79]])

Make assignments with 2D block(broadcastable array) -

In [40]: rand_arr = -np.arange(4).reshape(2,2)

In [41]: x[np.ix_(row_indices,col_indices)] = rand_arr

In [42]: x
Out[42]: 
array([[17, 39, 88, 14, 73, 58, 17, 78],
       [88,  0, 46, -1, 44, 81, 17, 67],
       [31, 70, 47, 90, 52, 15, 24, 22],
       [19, 59, 98, 19, 52, 95, 88, 65],
       [85, -2, 56, -3, 43, 79, 53, 37],
       [74, 46, 95, 27, 81, 97, 93, 69],
       [49, 46, 12, 83, 15, 63, 20, 79]])

2. Using np.ix_ with masks

Input array -

In [19]: x
Out[19]: 
array([[17, 39, 88, 14, 73, 58, 17, 78],
       [88, 92, 46, 67, 44, 81, 17, 67],
       [31, 70, 47, 90, 52, 15, 24, 22],
       [19, 59, 98, 19, 52, 95, 88, 65],
       [85, 76, 56, 72, 43, 79, 53, 37],
       [74, 46, 95, 27, 81, 97, 93, 69],
       [49, 46, 12, 83, 15, 63, 20, 79]])

Input row, col masks -

In [20]: row_mask = np.array([0,1,1,0,0,1,0],dtype=bool)

In [21]: col_mask = np.array([1,0,1,0,1,1,0,0],dtype=bool)

Make selections -

In [22]: x[np.ix_(row_mask,col_mask)]
Out[22]: 
array([[88, 46, 44, 81],
       [31, 47, 52, 15],
       [74, 95, 81, 97]])

Make assignments with scalar -

In [23]: x[np.ix_(row_mask,col_mask)] = -1

In [24]: x
Out[24]: 
array([[17, 39, 88, 14, 73, 58, 17, 78],
       [-1, 92, -1, 67, -1, -1, 17, 67],
       [-1, 70, -1, 90, -1, -1, 24, 22],
       [19, 59, 98, 19, 52, 95, 88, 65],
       [85, 76, 56, 72, 43, 79, 53, 37],
       [-1, 46, -1, 27, -1, -1, 93, 69],
       [49, 46, 12, 83, 15, 63, 20, 79]])

Make assignments with 2D block(broadcastable array) -

In [25]: rand_arr = -np.arange(12).reshape(3,4)

In [26]: x[np.ix_(row_mask,col_mask)] = rand_arr

In [27]: x
Out[27]: 
array([[ 17,  39,  88,  14,  73,  58,  17,  78],
       [  0,  92,  -1,  67,  -2,  -3,  17,  67],
       [ -4,  70,  -5,  90,  -6,  -7,  24,  22],
       [ 19,  59,  98,  19,  52,  95,  88,  65],
       [ 85,  76,  56,  72,  43,  79,  53,  37],
       [ -8,  46,  -9,  27, -10, -11,  93,  69],
       [ 49,  46,  12,  83,  15,  63,  20,  79]])
2 of 5
12

What about:

x[row_indices][:,col_indices]

For example,

x = np.random.random_integers(0,5,(5,5))
## array([[4, 3, 2, 5, 0],
##        [0, 3, 1, 4, 2],
##        [4, 2, 0, 0, 3],
##        [4, 5, 5, 5, 0],
##        [1, 1, 5, 0, 2]])

row_indices = [4,2]
col_indices = [1,2]
x[row_indices][:,col_indices]
## array([[1, 5],
##        [2, 0]])
🌐
Quora
quora.com › How-do-I-return-the-index-of-an-element-in-a-2D-array-in-Python
How to return the index of an element in a 2D array in Python - Quora
Answer (1 of 2): You don’t return the index - your code needs to keep track of where the elements are. If you are asking how do you search a 2D array - the only way is something like this: [code]def find_all(matrix, element): """Iterate through all row, column indexes in a 2D Matrix where ...
🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module3_IntroducingNumpy › AccessingDataAlongMultipleDimensions.html
Accessing Data Along Multiple Dimensions in an Array — Python Like You Mean It
# providing two numbers to access an element # in a 2D-array >>> grades[1, 0] # Brad's score on Exam 1 84 # negative indices work as with lists/tuples/strings >>> grades[-2, 0] # Brad's score on Exam 1 84 · We can also uses slices to access subsequences of our data. Suppose we want the scores of all the students for Exam 2. We can slice from 0 through 3 along axis-0 (refer to the indexing diagram in the previous section) to include all the students, and specify index 1 on axis-1 to select Exam 2: