0
0
Pythonprogramming~15 mins

List comprehension with if–else in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
List comprehension with if-else
📖 Scenario: You are working in a fruit store. You have a list of fruit names. You want to create a new list that shows if each fruit is 'Sweet' or 'Sour'. For this, you will use list comprehension with an if-else condition.
🎯 Goal: Create a list of fruits, then use list comprehension with if-else to label each fruit as 'Sweet' or 'Sour'. Finally, print the new list.
📋 What You'll Learn
Create a list called fruits with these exact values: 'apple', 'lemon', 'banana', 'lime', 'cherry'
Create a list comprehension called taste_labels that labels each fruit as 'Sweet' if the fruit is 'apple', 'banana', or 'cherry', otherwise 'Sour'
Print the taste_labels list
💡 Why This Matters
🌍 Real World
Stores and shops often need to categorize items quickly based on properties like taste, price, or availability. Using list comprehension with if-else helps automate this.
💼 Career
Understanding list comprehension with conditions is useful for data processing, filtering, and labeling tasks in many programming jobs.
Progress0 / 4 steps
1
Create the list of fruits
Create a list called fruits with these exact values: 'apple', 'lemon', 'banana', 'lime', 'cherry'
Python
Need a hint?

Use square brackets [] to create a list and separate items with commas.

2
Set up the sweet fruits list
Create a list called sweet_fruits that contains these exact fruits: 'apple', 'banana', 'cherry'
Python
Need a hint?

This list will help you check if a fruit is sweet or sour.

3
Create the list comprehension with if-else
Create a list comprehension called taste_labels that goes through each fruit in fruits and adds 'Sweet' if the fruit is in sweet_fruits, otherwise adds 'Sour'
Python
Need a hint?

Use the format: [value_if_true if condition else value_if_false for item in list]

4
Print the taste labels
Write a print statement to display the taste_labels list
Python
Need a hint?

Use print(taste_labels) to show the result.