Foundations
Lists
Storing Multiple Values
You're recording daily temperatures for a week: 72, 75, 68, 71, 73, 76, 74. Rather than creating 7 separate variables (day1, day2, ...), you store them in one list and access each by its position.
Create a list with values
Declare a list and fill it with initial values.
nums = [10, 20, 30, 40, 50]
print("nums=" + str(nums))
first = nums[0]
second = nums[1]
last = nums[4]
The list holds 5 numbers. We can print each one by its position. Position starts at 0, not 1 - this is called zero-based indexing.
Get elements by index
Access any element using its position number.
scores = [85, 92, 78, 95, 88]
print("scores=" + str(scores))
first = scores[0]
third = scores[2]
last = scores[4]
Put (change) elements
Modify values at specific positions.
nums = [1, 2, 3, 4, 5]
print("before: nums=" + str(nums))
nums[0] = 100
nums[2] = 300
print("after: nums=" + str(nums))
Lists can be modified after creation. Assign a new value to any position.
Fibonacci with lists
Store the entire Fibonacci sequence in one structure.
fib = [0] * 8
fib[0] = 0
fib[1] = 1
fib[2] = fib[0] + fib[1]
fib[3] = fib[1] + fib[2]
fib[4] = fib[2] + fib[3]
fib[5] = fib[3] + fib[4]
fib[6] = fib[4] + fib[5]
fib[7] = fib[5] + fib[6]
print("fib=" + str(fib))
Much cleaner than having c0, c1, c2... as separate variables.
Swap two elements
Exchange the first and last elements of a list.
nums = [10, 20, 30, 40, 50]
print("before: nums=" + str(nums))
temp = nums[0]
nums[0] = nums[4]
nums[4] = temp
print("after: nums=" + str(nums))
We need a temporary variable to hold one value during the swap. Without it, we'd lose one of the values.