Bird
0
0

You want AI to help improve this code that filters out empty strings from a list:

hard📝 Application Q15 of 15
AI for Everyone - AI for Professionals
You want AI to help improve this code that filters out empty strings from a list:
items = ["apple", "", "banana", "", "cherry"]
filtered = {len(item) for item in items if item}

What is the best AI suggestion to fix the code for correct output?
AChange curly braces {} to square brackets [] to create a list instead of a set
BRemove the if condition to include all items
CAdd a print statement inside the comprehension
DReplace len(item) with item.upper()
Step-by-Step Solution
Solution:
  1. Step 1: Understand the code's intention

    The code aims to filter out empty strings and get lengths of remaining items. Using curly braces creates a set, but the goal is likely a list of lengths.
  2. Step 2: Identify correct fix

    Changing {} to [] creates a list comprehension, producing a list of lengths for non-empty strings. Other options change logic or add invalid syntax.
  3. Final Answer:

    Change curly braces {} to square brackets [] to create a list instead of a set -> Option A
  4. Quick Check:

    Use [] for list comprehension, {} for set [OK]
Quick Trick: Use [] for lists, {} for dictionaries in comprehensions [OK]
Common Mistakes:
  • Confusing list and set comprehensions
  • Removing filters that exclude empty strings
  • Adding statements inside comprehensions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More AI for Everyone Quizzes