Review and practice
Create a list with square brackets.
Read or replace an item by its zero-based index.
Negative index -1 means the last item.
temps = [31, 34, 36]
temps[0] = 32
print(temps[1]) # 34
print(temps[-1]) # 36append adds one item at the end.
len returns the number of items.
in checks whether a value is present.
A slice selects a range; its end index is excluded.
codes = [200, 404]
codes.append(500)
print(len(codes)) # 3
print(404 in codes) # True
print(codes[0:2]) # [200, 404]What is printed?
levels = [4, 7, 9]
levels[1] = levels[0] + 2
print(levels)[4, 6, 9]Complete the two blanks so the final list is [18, 21, 24].
values = [18, 21]
values.____(24)
print(values[____]) # must print 21values.append(24)
print(values[1])For names = ["Ali", "Noor", "Sara", "Omar"], what do these expressions produce?
len(names)
names[1:3]4
["Noor", "Sara"]The program should print the last sensor reading. Why does it fail, and how do you fix it?
readings = [12.4, 12.7, 13.1]
print(readings[len(readings)])# len(readings) is 3; the last valid index is 2
print(readings[len(readings) - 1])
# or: print(readings[-1])The loop variable receives one list item at a time.
The indented block runs once per item.
Choose a variable name that describes one item.
voltages = [4.8, 5.0, 5.1]
for voltage in voltages:
print(voltage * 2)
# voltage = one readingrange generates a counting sequencerange(4) gives 0, 1, 2, 3.
Use the count as an index when the position matters.
Use direct iteration when only the values matter.
for i in range(4):
print(i, labels[i])
for label in labels:
print(label)Write a loop that calculates the sum of powers without using sum().
powers = [8, 12, 10, 15]total = 0
for power in powers:
total = total + power
print(total) # 45Create a list containing only temperatures greater than 35.
temps = [33, 37, 35, 39, 31]hot = []
for temp in temps:
if temp > 35:
hot.append(temp)
print(hot) # [37, 39]Increase every value in scores by 5. Modify the original list.
scores = [60, 72, 81]for i in range(len(scores)):
scores[i] = scores[i] + 5
print(scores) # [65, 77, 86]Print the index of "fault". Assume it appears once.
states = ["ok", "ok", "fault", "ok"]for i in range(len(states)):
if states[i] == "fault":
print(i) # 2