1.2.1.3 PCEP-30-02 Practice Test Compendium – Tuples and dictionaries
Tuples
01) A tuple, like a list, is a data aggregate that contains a certain number (including zero) of elements of any type. Tuples, like lists, are sequences, but they are immutable. You're not allowed to change any of the tuple elements, or add a new element, or remove an existing element. Attempting to break this rule will raise the TypeError
exception.
02) Tuples can be initialized with tuple literals. For example, these assignments instantiate three tuples – one empty, one one-element, and one two-element:
03) The number of elements contained in the tuple can be determined by the len()
function. For example, the following snippet prints 4
to the screen:
Note the inner pair of parentheses – they cannot be omitted, as it will cause the tuple to be replaced with four independent values and will cause an error.
04) Any of the tuple's elements can be accessed using indexing, which works in the same manner as in lists, including slicing.
05) An attempt to access a non-existent tuple element raises the IndexError
exception.
06) If any of the slice's indices exceeds the permissible range, no exception is raised, and the non-existent elements are not taken into consideration. Therefore, the resulting slice may be an empty tuple. For example, the following snippet outputs ()
to the screen:
07) The in
and not in
operators can check whether or not any value is contained inside the tuple.
08) Tuples can be iterated through (traversed) by the for
loop, like lists.
09) The +
operator joins tuples together.
10) The *
operator multiplies tuples, just like lists.
Dictionaries
01) A dictionary is a data aggregate that gathers pairs of values
. The first element in each pair is called the key, and the second one is called the value
. Both keys and values can be of any type.
02) Dictionaries are mutable but are not sequences – the order of pairs is imposed by the order in which the keys are entered into the dictionary.
03) Dictionaries can be initialized with dictionary literals. For example, these assignments instantiate two dictionaries – one empty and one containing two key:value
pairs:
Last updated