1.2.1.1 PCEP-30-02 Practice Test Compendium β Lists and strings
Lists
01) A list is a data aggregate that contains a certain number (including zero) of elements of any type.
02) Lists are sequences β they can be iterated, and the order of the elements is established.
03) Lists are mutable β their contents may be changed.
04) Lists can be initialized with list literals. For example, these two assignments instantiate two lists β the former is empty, while the latter contains three elements:
empty_list = []
three_elements = [1, 'two', False]05) The number of elements contained in the list can be determined by the len() function. For example, the following snippet prints 3 to the screen:
print(len(['a', 'b', 'c'])06) Any of the list's elements can be accessed using indexing. List elements are indexed by integer numbers starting from zero. Therefore, the first list element's index is 0 while the last element's index is equal to the list length minus 1. Using indices that are not integers raises the TypeError exception. For example, the following snippet prints a b c 0 1 2 to the screen:
the_list = ['a', 'b', 'c']
counter = 0
for ix in range(len(the_list)):
print(the_list[ix], end=' ')
the_list[ix] = counter
counter += 1
for ix in range(len(the_list)):
print(the_list[ix], end=' ')07) The list elements can be indexed with negative numbers, too. In this case, -1 accesses the last element of the list, and -2 accesses the one before the last, and so on. The alternative first list element's index is -len(list).
08) An attempt to access a non-existent list element (when the index goes out of the permissible range) raises the IndexError exception.
09) A slice is a means by which the programmer can create a new list using a part of the already existing list.
10) The most general slice looks as follows:
and selects those elements whose indices start at from, don't exceed to, and change with step. For example, the following snippet prints ['b', 'd'] to the screen:
11) The following assumptions are made regarding the slices:
the_list[from:to]is equivalent tothe_list[from:to:1]the_list[:to]is equivalent tothe_list[0:to]the_list[from:]is equivalent tothe_list[from:len(the_list)]the_list[:]is equivalent tothe_list[0:len(the_list)]
12) Slices β like indices β can take negative values. For example, the following snippet prints [1,2] to the screen:
Last updated