PythonPython ListsPython list construction

How do you create a list?

Question 77 of 88 · Updated

On this page

Create a list using square brackets, such as [1, 2, 3], or use the list(iterable) constructor to collect elements from an iterable. An empty list can be created using [] or list(). Use the construction method that matches the source of the elements and the intended ownership of the resulting collection.

The previous list fundamentals lesson explains what a list is. This lesson focuses on how a new list is constructed, how the source is evaluated or consumed, and how to avoid accidentally sharing elements or materializing an unbounded stream.

1. Create lists with square brackets#

PYTHON
empty = [] values = [2, 3, 2 + 3] print(empty, values) print([] is [])

Output:

[] [2, 3, 5]
False

A bracketed list display evaluates the supplied element expressions from left to right and stores their resulting object references in a newly created list. The expression 2 + 3 is evaluated during construction; it is not stored as unevaluated source code.

Each evaluation of an empty list display produces a distinct list. An empty list is useful when the number of elements is not yet known, or when constructing a result by accumulating values in a loop.

If a variable already references a list, assigning it to a second variable does not evaluate a new list display. It creates another binding to the existing object.

2. Construct a list from an iterable#

PYTHON
print(list((1, 2))) print(list(range(1, 6, 2))) print(list({'a': 1, 'b': 2})) print(list(b'AB'))

Output:

[1, 2]
[1, 3, 5]
['a', 'b']
[65, 66]

The built-in list type accepts zero arguments or one iterable argument. With no argument it creates an empty list. With an iterable it materializes elements in the order in which that iterable yields them.

The result depends on iteration semantics rather than merely the source object's appearance.

SourceConstructionElements obtained
Tuplelist((1, 2))Tuple elements
Rangelist(range(3))Generated integers
Stringlist('abc')Individual Unicode code-point strings
Byteslist(b'AB')Integer byte values
Dictionarylist(mapping)Keys in insertion order
Dictionary values viewlist(mapping.values())Values in iteration order
Dictionary items viewlist(mapping.items())Key-value tuples
Setlist()Elements in the set's iteration order

A set does not promise a sorted or application-defined sequence order. Use sorted when a meaningful sorted order is required and the elements support the requested ordering.

A list constructor does not parse structured text. For example, list('a,b') collects three characters, not two comma-separated fields. Use split for a simple literal delimiter or a parser for a structured format such as CSV.

3. Iterables, iterators and materialization#

A list is reusable as an iterable, but many sources of list elements are one-shot iterators.

PYTHON
source = iter([10, 20, 30]) print(next(source)) print(list(source)) print(list(source))

Output:

10
[20, 30]
[]

The explicit next call consumes the first item. The first list construction consumes all the remaining items. The second construction receives an exhausted iterator and creates an empty list.

Loading diagram…

A constructor can accept an object implementing the iterator protocol or an appropriate sequence protocol. It does not require the source to already be a list, and it does not generally need the caller to supply a separate length.

When construction consumes a generator, the generator's computation and side effects occur during construction. Exceptions from the source may propagate, and the source may have already advanced before an error occurs.

A list created from an existing list is a new outer container with references to the same elements. This is shallow construction, not a recursive duplication of its object graph. The dedicated copying lesson covers the distinction further.

4. Create a fixed number of elements or take a bounded prefix#

PYTHON
from itertools import count, islice print(list(islice(count(10), 4))) print([0] * 3) print([None] * 2)

Output:

[10, 11, 12, 13]
[0, 0, 0]
[None, None]

The count iterator produces an unbounded sequence. Calling list(count(10)) would attempt to consume that sequence indefinitely, eventually encountering a resource limit or interruption. The islice call above limits consumption to four values.

Sequence repetition is convenient when a list should initially contain repeated immutable values or placeholders. The expression [0] * 3 constructs a three-position list containing references to zero.

A zero or negative repetition count produces an empty list. Repetition does not independently construct a new object for every position: mutable repeated elements require special care.

5. Combine existing sources with unpacking or a comprehension#

PYTHON
first = [1, 2] second = (3, 4) print([0, *first, *second, 5]) print([n * n for n in range(4)])

Output:

[0, 1, 2, 3, 4, 5]
[0, 1, 4, 9]

A starred element inside a list display unpacks the elements of an iterable into the new list. Non-starred expressions contribute one element each. Multiple iterable sources can therefore be assembled into a single ordered collection.

Without the stars, a list display containing first and second would contain those collections themselves as nested elements, rather than their individual elements. Starred unpacking is one level deep; it is not a recursive flattening operation.

A list comprehension constructs a list by evaluating an expression for the items traversed by its clauses. It is useful when the output requires transformation or filtering rather than only copying the source elements. Later lessons cover comprehension syntax, scope, conditional expressions and performance in detail.

6. Practical construction: reject oversized iterable input#

When an application expects at most a certain number of elements, directly calling list on an untrusted iterable may allocate too much memory before validation can occur.

PYTHON
from itertools import islice def bounded_list(iterable, limit): if type(limit) is not int or limit < 0: raise ValueError('expected nonnegative integer limit') result = list(islice(iterable, limit + 1)) if len(result) > limit: raise ValueError('too many items') return result print(bounded_list(range(3), 3)) try: bounded_list(range(4), 3) except ValueError as exc: print(exc)

Output:

[0, 1, 2]
too many items

The function accepts a finite practical integer limit and reads at most one extra element to detect whether the limit is exceeded. The extra element is a deliberate look-ahead. Simply taking the first limit elements would truncate oversized input silently rather than reject it.

Loading diagram…

This helper rejects bool as a limit by requiring the exact int type. In an actual public interface, also impose a sensible upper bound on the limit itself: islice has an implementation-supported index range, and an enormous allowed list can still exhaust memory.

The bound is on the number of yielded elements, not on their byte size or execution time. A single next operation may block, raise an exception or allocate a large object. A production system may also need a byte budget, source timeouts and validation of each element.

The helper does not undo consumption of a one-shot source if it rejects the input. Use a different strategy if rollback or replay is required.

7. Construct independent mutable elements#

PYTHON
rows = [[] for _ in range(3)] rows[0].append('x') print(rows) shared = [[]] * 3 shared[0].append('x') print(shared)

Output:

[['x'], [], []]
[['x'], ['x'], ['x']]

In the comprehension, the inner list display is evaluated separately during each iteration. In the repetition expression, the single inner list is evaluated once and its reference is repeated three times.

Choose independent construction when each row or record must have its own mutable state. This is the same reference-sharing principle discussed in the earlier mutability and nested-loop lessons, applied here to list initialization.

For immutable placeholders such as None or integers, repetition is normally appropriate because those values cannot be changed in place.

8. Construction errors and complexity#

ExpressionResult or exception
list()New empty list
list(42)TypeError: integer is not iterable
list(None)TypeError: None is not iterable
list(1, 2)TypeError: too many positional arguments

If the desired list contains a single integer, use [42]. Do not pass the integer to list() as if the constructor accepted an arbitrary element. The constructor expects a source of elements, not a variable number of individual values.

For n elements from a finite iterable, list construction normally requires O(n) reference storage and O(n) collection work, assuming constant-cost iteration and ordinary CPython allocation behavior. The computation necessary to produce each element is additional. An iterable may offer a length hint to help allocate storage, but that is not a universal requirement or a guarantee of its actual element count.

A comprehension that computes expensive expressions must include their costs. Repetition and unpacking require enough storage for all resulting positions. The storage estimate for the list itself does not count all memory occupied by its referenced objects.

9. Choosing the right construction method#

RequirementAppropriate method
Known individual elementsList display: [a, b, c]
Empty collection[] or list()
Convert a finite iterablelist(iterable)
Assemble several iterable sourcesStarred list display
Transform or filter values during constructionList comprehension
Repeated immutable placeholdersSequence repetition
Independent mutable elementsRepeated evaluation with a comprehension
Take only a finite prefix of an iteratorlist(islice(source, count))

Use a list when materialized positional access or repeated traversal is useful. If the caller only needs to process each element once, a generator or iterator can avoid keeping the whole sequence in memory.

Interview-ready answer#

A Python list can be created with a square-bracket list display or with the list() constructor. A display evaluates its element expressions and stores references in a new list. The constructor accepts an iterable and materializes its yielded elements in order, consuming one-shot iterators. Starred unpacking assembles elements from several iterable sources, and comprehensions construct transformed or filtered results. Repetition initializes multiple positions but repeats references rather than independently creating mutable objects. For a finite source of n ordinary elements, materialization typically requires O(n) time and O(n) list reference storage; bound large or unbounded inputs before construction.

Official references#

Verification note: Seven runnable example groups matched their documented outputs on CPython 3.13.5 in independent namespaces. Three standalone TypeError tests passed, and 500 seeded randomized integer tuples produced 1,000 successful equivalence assertions comparing iterable construction, starred unpacking and repetition. Two triple-backtick fenced Mermaid diagrams were manually reviewed; the local Mermaid CLI was unavailable, so parser-level validation and public rendering were not performed. Official reference links are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design