0

I have two lists below

 list1 = ['a', 'b', 'c']
 list2 = [['a', 'b', 'c'], ['e', 'f', 'g']]

Now I have to find

Is list1 is list of list
Expected result "False"

Is list2 is list of list
Expected result is "True"

How to achieve this

2
  • 1
    Do heterogenous lists count as lists of lists if any of the elements are lists? For example, what should [[1,2,3], 1,2,3] return? Jun 27, 2018 at 22:10
  • @user3483203, True I am expected
    – meteor23
    Jun 27, 2018 at 22:11

2 Answers 2

8

If you want to know if anything in the list is a list:

any(isinstance(a, list) for a in list1) 

If you want to know if all the things in the list are lists:

all(isinstance(a, list) for a in list1)

This takes advantage of passing a generator expression to all().

1
  • 6
    you can even avoid the double parentheses: any(isinstance(a, list) for a in list1) It does stop calculation as soon as it finds a True. And it is more readable
    – Gelineau
    Jun 27, 2018 at 22:22
-4
list1 = ['a', 'b', 'c']
list2 = [['a', 'b', 'c'], ['e', 'f', 'g']]

print(type(list1[0]))
print(type(list2[0]))

Output:
<class 'str'>
<class 'list'>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.