0
0
Pythonprogramming~15 mins

Nested list comprehension in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Nested list comprehension
๐Ÿ“– Scenario: You work in a bakery that sells boxes of assorted cookies. Each box contains several types of cookies, and you want to create a simple list showing all cookie types available in all boxes.
๐ŸŽฏ Goal: Build a nested list comprehension to flatten a list of cookie boxes into a single list of cookie types.
๐Ÿ“‹ What You'll Learn
Create a list of lists called cookie_boxes with exact cookie types
Create a variable called all_cookies using nested list comprehension
Print the all_cookies list
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Bakeries and stores often have grouped data like boxes or categories. Flattening such data helps in searching or displaying all items easily.
๐Ÿ’ผ Career
Understanding nested list comprehension is useful for data processing jobs, where you often work with nested or grouped data structures.
Progress0 / 4 steps
1
Create the cookie boxes data
Create a list called cookie_boxes with these exact lists inside: ["chocolate chip", "oatmeal"], ["peanut butter", "snickerdoodle"], and ["sugar", "gingersnap"].
Python
Need a hint?

Remember, cookie_boxes is a list containing three lists, each with two cookie names as strings.

2
Prepare the variable for all cookies
Create an empty list called all_cookies to hold all cookie types before using list comprehension.
Python
Need a hint?

Just create a variable named all_cookies and set it to an empty list [].

3
Use nested list comprehension to flatten the list
Use nested list comprehension to fill all_cookies with every cookie from each box in cookie_boxes. Use all_cookies = [cookie for box in cookie_boxes for cookie in box] exactly.
Python
Need a hint?

Remember the order: first loop over each box in cookie_boxes, then over each cookie in that box.

4
Print the list of all cookies
Print the all_cookies list using print(all_cookies).
Python
Need a hint?

Use the print() function to show the list.