w3resource

Python: Count number of lists in a given list of lists

Python List: Exercise - 90 with Solution

Count Lists in Nested List

Write a Python program to count the number of lists in a given list of lists.

Visual Presentation:

Python List: Count number of lists in a given list of lists.

Sample Solution:

Python Code:

# Define a function 'count_list' that calculates the number of lists in the input list
def count_list(input_list):
    return len(input_list)

# Create two lists 'list1' and 'list2' containing sublists of varying depths
list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]]
list2 = [[2, 4], [[6, 8], [4, 5, 8]], [10, 12, 14]]

# Print a message indicating the original list
print("Original list:")

# Print the contents of 'list1'
print(list1)

# Print a message indicating the number of lists in the first list of lists
print("\nNumber of lists in said list of lists:")

# Call the 'count_list' function with 'list1' and print the result
print(count_list(list1))

# Print a message indicating the original list
print("\nOriginal list:")

# Print the contents of 'list2'
print(list2)

# Print a message indicating the number of lists in the second list of lists
print("\nNumber of lists in said list of lists:")

# Call the 'count_list' function with 'list2' and print the result
print(count_list(list2)) 

Sample Output:

Original list:
[[1, 3], [5, 7], [9, 11], [13, 15, 17]]

Number of lists in said list of lists:
4

Original list:
[[2, 4], [[6, 8], [4, 5, 8]], [10, 12, 14]]

Number of lists in said list of lists:
3

Flowchart:

Flowchart: Count number of lists in a given list of lists.

Python Code Editor:

Previous: Write a Python program to Zip two given lists of lists.
Next: Write a Python program to find the list with maximum and minimum length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-90.php