python: check if list is multidimensional or one dimensional

60,262

Solution 1

I think you just want isinstance ?

Example usage:

>>> a = [1, 2, 3, 4]
>>> isinstance(a, list)
True
>>> isinstance(a[0], list)
False
>>> isinstance(a[0], int)
True
>>> b = [[1,2,3], [4, 5, 6], [7, 8, 9]]
>>> isinstance(b[0], list)
True

Solution 2

According to the comments, you are converting your input to a numpy array anyway. Since np.array already handles figuring out how deeply the input lists are nested, it is easier to find out the number of dimensions from that array than from the nested lists.

In particular, arrays have a shape attribute which is a tuple of the lengths of the array along each dimension, so len(myarray.shape) will tell you the number of dimensions. eg,

>>> import numpy as np
>>> a = np.array([[1,2,3],[1,2,3]])
>>> len(a.shape)
2

Solution 3

If you like to find out how many dimensions a list has you can use this snippet of code:

def test_dim(testlist, dim=0):
   """tests if testlist is a list and how many dimensions it has
   returns -1 if it is no list at all, 0 if list is empty 
   and otherwise the dimensions of it"""
   if isinstance(testlist, list):
      if testlist == []:
          return dim
      dim = dim + 1
      dim = test_dim(testlist[0], dim)
      return dim
   else:
      if dim == 0:
          return -1
      else:
          return dim
a=[]
print test_dim(a)
a=""
test_dim(a)
print test_dim(a)
a=["A"]
print test_dim(a)
a=["A", "B", "C"]
print test_dim(a)
a=[[1,2,3],[1,2,3]]
print test_dim(a)
a=[[[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]]]
print test_dim(a)

Solution 4

This is very simplified solution. In most cases a multi-dimensional list/array/matrix would contain a list object in the first index. That being said, in python since you don't need to define the data type, this could return incorrect if your list looks something link: [1, [2,3], 4]. -- Otherwise it should work for all normal multi-dimensional lists.

def is2DList(matrix_list):
  if isinstance(matrix_list[0], list):
    return True
  else:
    return False
# list
list_1 = [1,2,3,4] # 1 x 4
list_2 = [ [1,2,3],[3,4,5] ] # 2 x 2
list_3 = [1, [2,3], 4]

print(is2DList(list_1)) # False
print(is2DList(list_2)) # True
print(is2DList(list_3)) # False - incorrect result

See it in action: https://trinket.io/python/a937fe2f00

Share:
60,262
user2129468
Author by

user2129468

Updated on July 09, 2022

Comments

  • user2129468
    user2129468 almost 2 years

    I am currently programing in python and I created a method that inputs list from the user, without knowing whether he is multidimensional or one dimensional. how do I check? sample:


    def __init__(self,target):    
        for i in range(len(target[0])):
            w[i]=np.random.rand(len(example[0])+1)
    

    target is the list. the problem is that target[0] might be int.