python: Parametered 2 dimentional list's size weather it meets my requirment or not

I wanted to check the passed two dimensional list meets my requirement.

def foo(twoDList):
 if len(twoDList) == 2:
   if len(twoDList[]) == 3:
     print("true")

Then while using the method:

a = [[1, 2, 3], [4, 5, 6]]
foo(a)  

Should have be true! How can I fix foo() for

len(twoDList) == 2 and all(len(sublist) == 3 for sublist in twoDList)

>Solution :

len(twoDList[]) gives me a syntax error, because you have to pass a index between the square brackets.

I assume you want each sublist have exactly three elements :

def foo(twoDList):
    if len(twoDList) == 2:
        if all(len(sublist) == 3 for sublist in twoDList):
            print("true")

If you want to raise an error if twoDList doesn’t meet the requirements, then use assert keyword :

def foo(twoDList):
    assert(len(twoDList) == 2 and all(len(sublist) == 3 for sublist in twoDList))
    print("true")

Hope I answered correctly !

[Edit] : I didn’t see @timgeb’s comment, I didn’t refresh this page before posting.

Leave a Reply