2

I want to know how can I check in the shortest way possible if a list contains lists inside. I don't need to check a value, just the type of the list. I want to know if the objects inside a list are lists or not. Just that.

Thank you!

8
  • You can sue isinstance to check if a variable is an instance of a specific type. Then you can loop through the elements individually, somethink like if isinstance(current_element, str) Commented Jun 3, 2019 at 12:02
  • Not duplicated, I don't want to know if a list is inside other list, I just want to know if the objects inside a list are lists or not. Commented Jun 3, 2019 at 12:04
  • What about list in map(type, your_list)? Commented Jun 3, 2019 at 12:05
  • @Nkolot What about ['a', []], there's one list but not all elements are list. Improve your question, what is the expected output? Do you want to know if all elements are lists? Or do you want to know if any elements are lists? Commented Jun 3, 2019 at 12:05
  • I want to know if the objects inside a list are lists or not. Just that. Commented Jun 3, 2019 at 12:06

4 Answers 4

9

Use isinstance(x, list) to see if x is an instance of list.

If you want to ensure that all elements in your list (let's call it my_list) are lists, use all():

all(isinstance(x, list) for x in my_list) 

If you just wanna know whether there are any lists inside of my_list, use any():

any(isinstance(x, list) for x in my_list) 

These both return a boolean value (True/False), so you can store it to a variable or use it in an if sentence or whatever:

if any(isinstance(x, list) for x in my_list): print('At least one list!') else: print('No lists in my_list') 
Sign up to request clarification or add additional context in comments.

Comments

0

A list can be mixed types, but you can find the type of any index in a list using the type method

x = [1, 2, 'three', [4, 5, 6]] # This list contains int, int, str, list for i in x: print(type(i)) 

Returns

<class 'int'> <class 'int'> <class 'str'> <class 'list'> 

Comments

0

you can check that with the isinstance method:

for example if you have a dictionary temp = {}

you can check that with

 print(isinstance(temp, dict)) # it ll return True if temp is a dictionary. 

same for list and strings etc...

Comments

0

To check if any of the items is a list you can do:

if list in map(type, my_list): # there is a list in `my_list` 

To check if all items are lists you can do:

if {list} == set(map(type, my_list)): # all items are lists 

You can be more explicit with:

def is_list(x): return type(x) == list 

And then:

if any(map(is_list, my_list)): # some items are lists 

Or:

if all(map(is_list, my_list)): # all items are lists 

Make sure to add your handling for the empty list case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.