Search code examples
pythonassert

Assert 2-d list in python


In python, I am trying to check if a given list is a 2-d list. I am supposed to use an assert statement but I don't know how to create one.

So far I have

assert type(x) == list

I know that this is incorrect and checks for a 1-d list. How do I fix this?


Solution

  • I did this...

    l=[[]] assert type(l) == list and type(l[0]) == list

    but I get an indexError for the one dimensional case so I used this instead...

    l=[]
    try:
        assert type(l) == list and type(l[0]) == list
    except IndexError:
            assert False
    
    Traceback (most recent call last):
      File "<stdin>", line 4, in <module>
    AssertionError
    

    Maybe there is a better way but it's not obvious to me.

    A better (but long winded) way might be...

     assert type(l) == list and len({ type(el) for el in l }) == 1 and { type(el) for el in l }.pop() == list