Menu
CoddyTech

Recap - House Of Lists

Part of the Logic & Flow section of Coddy's Python journey. Lesson 54 of 78.

challenge icon

Challenge

Easy

Create a function named house_of_lists that takes a list of lists list_of_lists as an argument. Each inner list contains numbers. The function should use list comprehensions to perform the following operations:

  1. Filter out inner lists that have a sum greater than 50, keeping only those whose sum is 50 or less.
  2. From the remaining inner lists, extract numbers that are less than 5.
  3. Combine all extracted numbers into a single list.
  4. Return the combined list of numbers.

New here: one comprehension can loop over a list of lists with two for clauses. The first for takes each inner list from the outer list, the second takes each number from that inner list:

outer = [[1, 2], [3, 4], [5, 6]]
flat = [num for inner in outer for num in inner]
print(flat)  # [1, 2, 3, 4, 5, 6]

Try it yourself

def house_of_lists(list_of_lists):
    # Write code here

All lessons in Logic & Flow

Practice on your own: Online Python compiler