Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings
What this domain covers
This domain tests the four built-in collections and strings: indexing, slicing, mutability, core methods, and which operations raise errors. Expect "what is the output" questions involving aliasing and in-place methods.
Core rules
- Lists are ordered and mutable:
a[i],a[i:j], negative indices,len(),in. Methods includeappend,extend,insert,pop,remove,sort,reverse.sort()modifies in place and returnsNone. - Tuples are ordered and immutable. A one-element tuple needs a comma:
(5,). Unpacking:a, b = 1, 2. - Sets hold unique, hashable elements and are unordered.
{}is an empty dict;set()is an empty set. Operators:|union,&intersection,-difference,^symmetric difference;add,discard(no error if absent),remove(raisesKeyError). - Dictionaries map hashable keys to values, preserve insertion order, and support
d[k],get(k, default),keys(),values(),items(), andin(checks keys).d[k]on a missing key raisesKeyError. - Strings are immutable sequences:
s[0], slicing,in,+,*, and methods such asupper,strip,split,join,replace,find. Every method returns a new string.
Worked example
a = [3, 1, 2]; b = a; b.sort(); print(a) prints [1, 2, 3]. b = a copies the reference, not the list, so both names point to the same object. For an independent list use b = a[:], a.copy() or list(a).
Traps
a = baliases; slicing copies.x = a.sort()makesxequal toNone.- Negative indices count from the end; slices never raise
IndexError. s[0] = "H"fails because strings are immutable.- Adding a list to a set raises
TypeErrorbecause lists are unhashable.