22 Lists
22 Lists
value 12 49 -2 26 5 17 -6
value 0 0 0 0
List initialization
value 0 0 0
Accessing elements
name[index] # access
name[index] = value # modify
• Example:
numbers = [0] * 2
numbers[0] = 27
numbers[1] = -6
print(numbers[0])
if (numbers[1] < 0):
print("Element 1 is negative.")
index 0 1
value 27 -6
Out-of-bounds
• Legal indexes to use []: between – list's length and the list's length - 1.
• Reading or writing any index outside this range with [] will cause an
IndexError: list assignment index out of range
• Example:
data = [0] * 10
print(data[0]) # okay
print(data[9]) # okay
print(data[-20]) # error
print(data[10]) # error
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
Lists and for loops
• It is common to use for loops to access list elements.
for i in range(0, 8):
print(str(numbers[i]) + " ", end='')
print() # output: 0 4 11 0 44 0 0 2
• Sometimes we assign each element a value in a loop.
for i in range(0, 8):
numbers[i] = 2 * i
index 0 1 2 3 4 5 6 7
value 0 2 4 6 8 10 12 14
len()
• Use len() to find the number of elements in a list.
index 0 1 2 3 4 5 6
value 1 7 10 12 8 14 22