Search code examples
pythonpython-3.xlistif-statementmethods

python: Parametered 2 dimentional list's size whether it meets my requirement 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 an 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")