← Core Concepts
Concept
len(), sum(), min(), max() — useful built-in functions
Common functions for working with sequences and numbers.
len() — get length
# Length of sequences:
print(len([1, 2, 3])) # 3
print(len("hello")) # 5
print(len({'a': 1, 'b': 2})) # 2 (number of keys)
sum() — add numbers
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # 15
# With start value:
total = sum(numbers, 10) # Start from 10
print(total) # 25
min() — find minimum
numbers = [3, 1, 4, 1, 5]
smallest = min(numbers)
print(smallest) # 1
# With key function:
words = ['apple', 'pie', 'a']
shortest = min(words, key=len)
print(shortest) # 'a'
max() — find maximum
numbers = [3, 1, 4, 1, 5]
largest = max(numbers)
print(largest) # 5
# With key function:
words = ['apple', 'pie', 'banana']
longest = max(words, key=len)
print(longest) # 'banana'
Multiple arguments
# Can pass multiple values:
print(min(3, 1, 4)) # 1
print(max(3, 1, 4)) # 4
print(sum([1, 2], [3, 4])) # Error! sum only works with numbers