Python Glossary Русский

all Python 3Lists (list)term

Creating a list

creation

A list is written as the [] literal, with the list() constructor, or as a list comprehension. It may hold items of any type.

Syntax

[]  |  list()  |  list(iterable)  |  [expr for x in iter]

list() applied to a string splits it into characters: list('abc') gives ['a', 'b', 'c'], not a one-item list — use the literal for that. Also note that multiplication copies references, not objects: [[]] * 3 holds the same inner list three times, so appending to the "first" row shows up in all of them; build matrices with a comprehension instead.

Examples

a = []
# → []
b = [1, 2, 3]
# → [1, 2, 3]
c = list('abc')
# → ['a', 'b', 'c']
d = list(range(5))
# → [0, 1, 2, 3, 4]
e = [x**2 for x in range(4)]
# → [0, 1, 4, 9]
f = [1, 'two', 3.0, None]
# → [1, 'two', 3.0, None]
g = [0] * 5
# → [0, 0, 0, 0, 0]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy