list is Python’s most common container. Wrapped in square brackets [], its items can be changed, can repeat, and keep their insertion order.
Create a list first, then loop through it with for.
my_list = [10, 20, 30, 40, 50]
for value in my_list:
print(value)output:
10 20 30 40 50
append() adds a new item to the end; prices[1] reads the second item by index (index starts at 0).
prices = [100, 102, 99]
prices.append(105) # 加到結尾
print(prices[1]) # 102(index 1)output:
102
pop(index): removes and returns the item at that index (defaults to the last one if omitted).
prices = [100, 102, 99, 105]
prices.pop(2) # 移除 index 2 的 99,並回傳
print(prices) # [100, 102, 105]output:
[100, 102, 105]
remove(value): deletes the first item equal to value.
prices = [100, 102, 99, 105]
prices.remove(99) # 刪掉第一個 99
print(prices) # [100, 102, 105]output:
[100, 102, 105]
del prices[index]: deletes by index, doesn’t return anything.
prices = [100, 102, 99]
del prices[0] # 刪掉 100
print(prices) # [102, 99]output:
[102, 99]
Use sum() to add up and len() to count, to get the average.
race_times = [72.5, 74.2, 71.8, 73.1]
avg_time = sum(race_times) / len(race_times)
print(f"Average time: {avg_time:.1f}s") # 72.9soutput:
Average time: 72.9s
