Know if there are lists of lists or not - Python

Suppose we have two lists:

A = [2, 3, [6, 7], 0]
B = [4, 7, 10, 2]

I want to input those values to a function like this:

def gettype(self, a):
 for x in a:
    if isinstance(x, list):
     ident = True
    else:
     ident = False
  return ident 

That returns True if there are a list of lists or false otherwise.

ident = gettype(A)
print ident
True

ident = gettype(B)
print ident
False

PS: That function above doesn't work, it's returning False in both cases

Upvotes: 1

Views: 102

Answers (4)

Junuxx
Junuxx

Reputation: 14251

The problem is that you change the value of ident for every member of the list. So in fact you only get True if the last element of the list is a list.

Try this instead. If there is a list in the list, return True. If the end of the list is reached without encountering a list, return False.

def gettype(self, a):
 for x in a:
    if isinstance(x, list):
     return True
  return False

Upvotes: 4

Greg E.
Greg E.

Reputation: 2742

The issue with your code is that you update ident on each iteration, and the last value in A is not a list, hence the False result. Here's what you likely want:

def gettype(self, a):
    for x in a:
        if isinstance(x, list):
            return True
    return False

Notice that the return True statement immediately breaks out of the for loop and terminates the algorithm as soon as a list element is encountered.

Upvotes: 1

georg
georg

Reputation: 214949

Like

A = [2, 3, [6, 7], 0]
B = [4, 7, 10, 2]


def has_lists(lst):
    return any(isinstance(x, list) for x in lst)

print has_lists(A) # True
print has_lists(B) # False

Upvotes: 10

Diego Navarro
Diego Navarro

Reputation: 9704

You are iterating over all elements of the list. The problem is you are overwriting the value of ident and as the last value of the list is an integer the function returns False.

You have to return True when you find the first case of list element like the other implementations in the other answers do.

Upvotes: 1

Related Questions