Mastering Python sum() Function
The sum() function in Python is one of the most frequently used built-in functions. While it’s often used to sum numbers in a list, it can also count booleans or aggregate values from a comprehension.
Mastering Python sum() Function ๐ก
✅ Basic List Summation
The most common use is to total a list of numbers.
nums = [1, 2, 3, 4, 5]
total = sum(nums)
print(total) # 15
✅ Count True Values in a Boolean List
Because True equals 1 and False equals 0, sum can count how many True values exist.
values = [True, False, True]
count_true = sum(values)
print(count_true) # 2
✅ Use with List Comprehension
Sum works perfectly with generator expressions for custom aggregations.
word_lengths = sum(len(word) for word in ["hello", "world"])
print(word_lengths) # 10
From counting flags to totaling word lengths, sum() is a small but powerful tool that makes your Python code cleaner and faster.
"Simplicity in code creates space for clarity. Use Python's built-ins to write less and express more." — CodeVerse
Comments
Post a Comment