Accessing Elements¶
The syntax for accessing the elements of a list is the same as the syntax for
accessing the characters of a string. We use the index operator ( []
– not to
be confused with an empty list). The expression inside the brackets specifies
the index. Remember that the indices start at 0. Any integer expression can be used
as an index and as with strings, negative index values will locate items from the right instead
of from the left.
1
numbers = [17, 123, 87, 34, 66, 8398, 44]
2
print(numbers[2])
3
print(numbers[9 - 8])
4
print(numbers[-2])
5
print(numbers[len(numbers) - 1])
6
Check your understanding
list-4-1: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[5])
list-4-2: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[2].upper())
list-4-3: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[2][0])