Materialize iterable data
Materialize an iterable so it can be indexed, sliced, or traversed repeatedly.
Python · Class
list is Python’s mutable sequence type. Create one with a literal, comprehension, or list(iterable); construction preserves the iterable’s item order.
list creates a mutable sequence, either empty or populated from an iterable. Its elements preserve the iterable’s order, and the sequence supports indexing, slicing, iteration, concatenation, repetition, and in-place mutation.
list([iterable])| Name | Type | Description |
|---|---|---|
iterable | iterable | Optional iterable whose items populate the new list in iteration order. |
A new list containing the iterable’s items in the same order; with no argument, an empty list.
list is one of Python’s three basic sequence types, alongside tuple and range.[] to create an empty list.append, extend, sort, and reverse return None, not the list.numbers = list(range(1, 4))
numbers.append(4)
print(numbers) # [1, 2, 3, 4]Creates a list from an iterable, then mutates it by appending one item.
Materialize an iterable so it can be indexed, sliced, or traversed repeatedly.
Collect values produced by a comprehension or loop for later processing.
Maintain an ordered, mutable collection whose contents change over time.
list constructor do?list(iterable) accepts an iterable and creates a new list containing the iterable’s items in the same order. The iterable can be a sequence, another container that supports iteration, or an iterator object.
Follow-up: What happens with an iterator? It is consumed as the list is built, so later iteration begins wherever that iterator was left.
A list is a mutable sequence, so its elements can be changed after creation. Lists are commonly used for collections whose items are generally homogeneous, although Python does not enforce a single element type.
Follow-up: How would you prevent accidental mutation? Use a tuple for a fixed sequence, or expose an immutable interface where appropriate.
Lists support square-bracket literals, list comprehensions, and the list() or list(iterable) constructor. An empty list can be written as [], while items in a literal are separated by commas.
Follow-up: When is a comprehension preferable? Use it when transforming or filtering an iterable concisely; use list(iterable) when direct materialization is all that is needed.
tuplerangedictsetcollections