user2384994
user2384994

Reputation: 1847

How to define a two-dimensional list in Python like this?

In my understanding, two-dimensional list in Python is just a list of lists, so a two-dimensional list can be defined as follows:

a=[[0,0],[1,1]]

To get an element of this two-dimensional list, we have to write

a[0][1]

while the following form

a[0,1]

will cause an error. That is, indexes should be separated by [], instead of being putting together in one [] separated by comma.

However, in page 59 of the book "Python Essential Reference", Fourth Edition, David M. Beazley, I read:

enter image description here

In the image above, we can see that multidimensional list can be written in the form of, say, m[1:10, 3:20]. But how to define such a two-demensional list in Python so that we can get an element using m[1,2] form? Thanks.

Upvotes: 2

Views: 2755

Answers (3)

Blender
Blender

Reputation: 298106

That is, indexes should be separated by [], instead of being putting together in one [] separated by comma.

a[0,1] is equivalent to a[(0, 1)], which calls a.__getitem__((0, 1)).

a[0][1] is equivalent to a.__getitem__(0).__getitem__(1). As you can see, the brackets are really just a nice way of calling __getitem__.

Python lists only support integers and slice objects as the arguments to __getitem__, so you can't write a[0, 1]. You can, however, write your own class and have __getitem__ do whatever you want:

>>> class Something(object):
...     def __getitem__(self, arg):
...         return arg
...     
>>> Something()[{1, 2, 3}, {4, 5, 6}, 'foo', ..., 12, 4:2]
    ({1, 2, 3}, {4, 5, 6}, 'foo', Ellipsis, 12, slice(4, 2, None))

Upvotes: 3

Thorsten Kranz
Thorsten Kranz

Reputation: 12755

Even though Python lists do not have more than one dimension the notation with two or more indices / slices is needed for arrays / matrices which come with numpy. Even though it (intentionally) doesn't belong to the core library it has become a de facto standard for n-dimensional arrays.

Here you can type

>>> import numpy as np
>>> ar = np.array([[1,2],[3,4]])
>>> ar[0,0]
1
>>> ar[:,0]
array([1, 3])

>>> random_array = np.random.random((100,100))
>>> random_array[50:60,30:35]
array([[ 0.8352567 ,  0.14901839,  0.2409099 ,  0.88278442,  0.84300552],
       [ 0.88403713,  0.54964811,  0.83500869,  0.88258427,  0.90273584],
       [ 0.00271817,  0.94116153,  0.6282039 ,  0.3243262 ,  0.71785796],
       [ 0.0661821 ,  0.99243509,  0.5888741 ,  0.04161134,  0.89517395],
       [ 0.87419943,  0.14761041,  0.06123542,  0.8139316 ,  0.66220133],
       [ 0.24710625,  0.02305463,  0.7301232 ,  0.11279152,  0.57674316],
       [ 0.9893136 ,  0.9711931 ,  0.12936097,  0.49021876,  0.24834283],
       [ 0.48277394,  0.76470469,  0.29348414,  0.43578663,  0.69670601],
       [ 0.43401812,  0.14714134,  0.52015761,  0.40088974,  0.25203087],
       [ 0.9431969 ,  0.04824567,  0.98400652,  0.1129802 ,  0.25518842]])

Custom classes seem to be a very special use case - numpy arrays are really used a lot, almost no scientific Python library does not use numpy.

Upvotes: 3

Sassan
Sassan

Reputation: 2339

A class like this handles it:

class List(list):
  def __getitem__(self, index):
    if type(index) is int:
      return super(List, self).__getitem__(index)
    l = self
    for i in index:
      if not isinstance(l, list)
        raise IndexError('Too many indexes: out of depth.')
      l = l[i]
    return l

You can use it like this:

>>> l = List([[1,2,3],[3,2,1]])
>>> print l[1,2]

Upvotes: 2

Related Questions