Guide Python Beginner

10.2 Creating Lists

Empty lists, list literals, the list() constructor, splitting a string into characters, materializing a range(), and building nested or mixed-type lists.

2 min read

Empty Lists

The starting point for building up a collection incrementally, e.g. inside a loop.

>>> items = []
>>> items
[]

List Literals

The most common way to create a list with known contents up front — square brackets with comma-separated values.

>>> nums = [1, 2, 3]

list()

The list() constructor converts any iterable — string, tuple, range, set — into a list, covered in depth in 8.6 Collection Type Conversion.

>>> list((1, 2, 3))
[1, 2, 3]

Lists from Strings

Passing a string to list() splits it into its individual characters — a different result than str.split(), which splits by word or delimiter (see 9.7 Common String Methods).

>>> list("abc")
['a', 'b', 'c']

range()

range() alone is lazy — wrapping it in list() actually materializes the numbers as a real list (see 5.4 Sequence Data Types).

>>> list(range(5))
[0, 1, 2, 3, 4]

Nested Lists

A list can contain other lists as elements — the basis for representing grids, matrices, and tables; see 10.10 Nested Lists and Matrices.

>>> grid = [[1, 2], [3, 4]]

Mixed Data Types

Unlike arrays in many other languages, a single Python list can freely mix types.

>>> mixed = [1, "two", 3.0, True]

Quick Interview Answer

“A list literal ([1, 2, 3]) is the common case for known contents. list() converts any iterable — a string becomes its individual characters, not words, which trips people up if str.split() was actually intended. range() is lazy on its own; list(range(...)) is what actually materializes the numbers. Lists can nest freely and mix types, since every slot is just a same-sized reference regardless of what it points to.”

Common Mistakes

  • Calling list("hello world") expecting a list of words — it produces a list of individual characters, including the space; str.split() is the word-splitting tool.
  • Materializing a large range() into a list() unnecessarily, losing its lazy memory efficiency for no reason.
  • Writing [[0] * 3] * 3 to build a 3×3 grid of independent rows — * on a list repeats references to the same inner list, so mutating one row mutates all of them (see 10.10 Nested Lists and Matrices for the correct pattern).

Add More Questions to This Guide

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

Open Google Form