Guide Python Beginner

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.

2 min read
flowchart TD STR["str"] <--> INT["int"] STR <--> FLOAT["float"] INT <--> FLOAT STR <--> COLL["list / tuple / set"] BOOL["bool"] --> INT BOOL --> FLOAT

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(), and dict() all accept any iterable — a string, another collection, a range, dict keys — and build a new collection of their own type from it. set() and frozenset() are the standard deduplication idiom, dropping duplicates automatically. dict() specifically expects an iterable of key-value pairs, like a list of 2-tuples. range is unusual: nothing converts into it, but it’s frequently converted from, via list(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 a list() 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, hitting TypeError: unhashable type.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form