Can items of a list be accessed in any order?


#1

Question

This exercise asks to print a particular index of a list. Can list elements be accessed in any order?

Answer

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])

#2

The above example may print repeated items. Below will generate a random list…

>>> from random import randrange
>>> randlist = []
>>> while len(randlist) < len(elements):
	x = randrange(0, len(elements))
	if elements[x] not in randlist:
		randlist.append(elements[x])

		
>>> randlist
['Helium', 'Nitrogen', 'Hydrogen', 'Carbon', 'Oxygen']
>>>