Lists & Loops
Lists are used for representing a collection of values.
numbers = [1, 2, 3, 4, 5]
print(numbers)
We use a for loop to iterate over a list of values.
numbers = [1, 2, 3, 4, 5]
for n in numbers:
print(n)
Try changing the above program to print the squares of numbers instead of the numbers.
We can find the length of a list using the built-in function len
.
numbers = [1, 2, 3, 4, 5]
print(len(numbers))
Example: sum
Pytho has a built-in function sum
to compute the sum of a list of numbers.
numbers = [1, 2, 3, 4, 5]
print(sum(numbers))
Let's try to implement our own version of sum. Let's call it my_sum
.
def my_sum(values):
result = 0
for v in values:
result = result + v
return result
numbers = [1, 2, 3, 4, 5]
print(my_sum(numbers))
Can you write a function product
to compute the product.
def product(values):
# FIX ME
return 0
numbers = [1, 2, 3, 4, 5]
print(product(numbers))