# 10.4. 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.

list-4-1: What is printed by the following statements?

alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[5])

• (A) [ ]
• The empty list is at index 4.
• (B) 3.14
• Yes, 3.14 is at index 5 since we start counting at 0 and sublists count as one item.
• (C) False
• False is at index 6.

list-4-2: What is printed by the following statements?

alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[2].upper())

• (A) Error, you cannot use the upper method on a list.
• alist[2] is the string cat so the upper method is legal
• (B) 2
• 2 is the index. We want the item at that index.
• (C) CAT
• Yes, the string cat is upper cased to become CAT.

list-4-3: What is printed by the following statements?

alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[2][0])

• (A) 56
• Indexes start with 0, not 1.
• (B) c
• Yes, the first character of the string at index 2 is c
• (C) cat
• cat is the item at index 2 but then we index into it further.
• (D) Error, you cannot have two index values unless you are using slicing.
• Using more than one index is fine. You read it from left to right.
Next Section - 10.5. List Membership