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!
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') 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.
isinstanceto check if a variable is an instance of a specific type. Then you can loop through the elements individually, somethink likeif isinstance(current_element, str)list in map(type, your_list)?['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?