Python Glossary Русский

all Python 3Lists (list)term

+ concatenation / * repetition of lists

operators

The + operator returns a new list — the concatenation of the two. * repeats a list n times without copying the items: it repeats references to the same objects.

Syntax

lst1 + lst2  |  lst * n

Both operators build a whole new list, so accumulating with res = res + [x] inside a loop is quadratic — use append() or extend(). Also keep lst += other apart from lst = lst + other: += mutates in place like extend, so everyone holding a reference to that list sees the change, and it accepts any iterable on the right; plain + insists on another list and raises TypeError otherwise.

Examples

print([1, 2] + [3, 4])
# → [1, 2, 3, 4]
print([0] * 5)
# → [0, 0, 0, 0, 0]
print(['a', 'b'] * 3)
# → ['a', 'b', 'a', 'b', 'a', 'b']
print([1, 2] + [])
# → [1, 2]
trap = [[]] * 3
trap[0].append(1)
print(trap)
# → [[1], [1], [1]] (одна ссылка!)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy