Bird
0
0

Given a list data = [3, 0, 5, '', None, 7], which code correctly counts only the items that are considered 'truthy' in Python?

hard📝 Application Q15 of 15
Python - Magic Methods and Operator Overloading
Given a list data = [3, 0, 5, '', None, 7], which code correctly counts only the items that are considered 'truthy' in Python?
Acount = len(data)
Bcount = sum(data)
Ccount = sum(1 for x in data if x)
Dcount = len([x for x in data if x == True])
Step-by-Step Solution
Solution:
  1. Step 1: Understand 'truthy' values in Python

    Truthy values are those that evaluate to True in conditions; 0, '', and None are falsy.
  2. Step 2: Analyze each option

    count = len(data) counts all items, ignoring truthiness. count = sum(1 for x in data if x) sums 1 for each truthy item, correctly counting them. count = sum(data) sums values, not counts. count = len([x for x in data if x == True]) checks for exact True, missing other truthy values.
  3. Final Answer:

    count = sum(1 for x in data if x) -> Option C
  4. Quick Check:

    Sum 1 for truthy items counts them correctly [OK]
Quick Trick: Use sum with condition to count truthy items. [OK]
Common Mistakes:
  • Using len() counts all items, not just truthy
  • Summing values instead of counting
  • Checking equality to True instead of truthiness

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes