With a list, you can simply use the []
operator again. So, for example:
>>> a = [[1,2], [3, 4]]
>>> a[0][0]
1
>>> a[0][1]
2
>>> a[1][0]
3
>>> a[1][1]
4
>>> type(a)
<type 'list'>
>>> type(a[0])
<type 'list'>
>>> type(a[0][0])
<type 'int'>
The explanation is simple, the first time, you use the []
operator, you get a list
, so you can use the []
operator again. Like this, you can emulate a matrix.
If you want to find the indexes, then you can use this nifty little function:
def finder(value_to_find, matrix):
for r, row in enumerate(matrix):
for c, col in enumerate(row):
if col == value_to_find:
return r, c
And, for a demo:
>>> a = [[1,2], [3, 4]]
>>> a[0][0]
1
>>> a[0][1]
2
>>> a[1][0]
3
>>> a[1][1]
4
>>> def finder(value_to_find, matrix):
for r, row in enumerate(matrix):
for c, col in enumerate(row):
if col == value_to_find:
return r, c
>>> finder(4, a)
(1, 1)
And here is an explanation with comments:
def finder(value_to_find, matrix):
"""
Function to find the indexes of a given value, on first notice
@param value_to_find: The value we need to find
@param matrix: The matrix we are to work with
@return: A tuple of row, column
"""
# Looping over the rows (lists within the main matrix)
for r, row in enumerate(matrix): # Using enumerate returns the index, r and the value row (which is a list)
for c, col in enumerate(row): # Looping over the values in each row, with index c and value col
if col == value_to_find: # If the col is equal to the value we want, then we return the row, column tuple
return r, c
If you have a 1-D matrix, then you can look at this solution from Hyperborius:
listindex = row * length_of_row + column