8.6 Collection Type Conversion
Converting between list, tuple, set, frozenset, dict, and range — the standard deduplication idiom, and how each conversion function treats its input as an iterable.
Common conversion paths between core Python types.
list()
Converts any iterable (string, tuple, set, range, dict keys, …) into a list.
>>> list("abc")
['a', 'b', 'c']
tuple()
Converts any iterable into an immutable tuple — useful when a fixed, hashable version of a collection is needed. See 5.9 Mutable vs Immutable Types.
>>> tuple([1, 2, 3])
(1, 2, 3)
set()
Converts any iterable into a set, automatically removing duplicates — the standard one-line deduplication idiom.
>>> set([1, 1, 2, 3])
{1, 2, 3}
frozenset()
The immutable counterpart to set() — produces a set that can itself be used as a dict key or set member. See 5.6 Set Data Types.
>>> frozenset([1, 2, 3])
frozenset({1, 2, 3})
dict()
Converts an iterable of key-value pairs (like a list of 2-tuples) into a dict.
>>> dict([("a", 1), ("b", 2)])
{'a': 1, 'b': 2}
range()
Not exactly a “conversion” target (nothing converts into range), but frequently converted from — generates numbers lazily, and list(range(...)) materializes them:
>>> list(range(5))
[0, 1, 2, 3, 4]
Quick Interview Answer
“
list(),tuple(),set(),frozenset(), anddict()all accept any iterable — a string, another collection, arange, dict keys — and build a new collection of their own type from it.set()andfrozenset()are the standard deduplication idiom, dropping duplicates automatically.dict()specifically expects an iterable of key-value pairs, like a list of 2-tuples.rangeis unusual: nothing converts into it, but it’s frequently converted from, vialist(range(...)), to materialize its lazily generated numbers.”
Common Mistakes
- Passing a plain list of values (not pairs) to
dict()expecting it to work — it requires an iterable of key-value pairs, like[(k1, v1), (k2, v2)], and raises otherwise. - Materializing a large
range()into alist()unnecessarily, losing its lazy memory efficiency for no reason (see 5.4 Sequence Data Types). - Converting a list with unhashable elements (like nested lists) to a
set, hittingTypeError: unhashable type.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form