This exercise asks to print a particular index of a list. Can list elements be accessed in any order?
Yes, list elements can be accessed in any order so long as the index used is valid. Valid indexes for a list are values from 0 through
len() - 1 of the list. The following example shows a list whose items are randomly accessed using the
randint() function. As long as the value returned by
randint() is between 0 and
len() -1 for the list, there is no issue accessing the list items. If the index used is greater than
len() -1 for the list, then an
IndexError will occur.
The exception to this is the use of a negative index. A negative index will return an element from the end of the list without needing to know how many items are in the list.
from random import randint elements = ['Hydrogen', 'Helium', 'Carbon', 'Oxygen', 'Nitrogen'] for count in range(10): index = randint(0, len(elements) - 1) print(elements[index])