liveBook · Manning

List()

As explained in The Quick Python Book, Fourth Edition

The list function is a Python built-in constructor that creates a new list from an iterable or sequence of elements.

`list()` creates a new list from a sequence. Use it when you need list operations on elements currently held in another sequence: `list((1, 2, 3, 4))` gives `[1, 2, 3, 4]`. The reverse conversion uses `tuple()`. section 5.7.4

Turn characters into an editable list

`list("Hello")` gives `['H', 'e', 'l', 'l', 'o']`. To edit a string character by character, convert it with `list()`, change the list, then join the characters with `"".join(...)`. This creates new objects, so it may be costly when repeated millions of times. section 5.7.4 section 6.4.6

`list()` is also useful when a result can be iterated over but is not itself a list. For example, `zip()` returns an iterator: a CSV writer can use it directly, but converting it with `list()` lets you inspect the paired values as a list. Dictionary `keys()`, `values()`, and `items()` return dynamically updated views; `list()` makes a list of their contents. section 22.5.2 section 7.2

If you already have the elements to write out, square brackets are simpler: `x = [1, 2, 3]`. Use `list()` for conversion rather than as a substitute for every list literal. section 5.1 section 5.7.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates conversion through short examples; does not develop constructor internals.
Examples
Shows a tuple becoming a list, a string becoming characters, and dictionary views appearing as lists.
What it assumes
Assumes familiarity with calling Python functions; teaches conversion through concrete tuple and string examples.
What you can do after
Apply it via Python’s built-in list() to turn a sequence or iterable result into a list for inspection or modification.
How it connects
Links list() to tuples, strings, string joining, zip iterators, and dictionary views.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.