[lang-ref] ( init_with_size ) ( python )
def test_init_with_size():
# items = [x] * n
items = ['Camera!'] * 3
assert items == ['Camera!', 'Camera!', 'Camera!']
def test_init_with_size_alternative():
# this is trap.
items = [['a', 'b']] * 3
assert items == [['a', 'b'], ['a', 'b'], ['a', 'b']]
assert items[0] is items[1] # same object ...
items[0].append('c') # so this changes all elements
assert items == [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
# this is safe.
items = [['a', 'b'] for _ in range(3)] # distinct objects
assert items == [['a', 'b'], ['a', 'b'], ['a', 'b']]
assert items[0] is not items[1] # different objects
items[0].append('c') # this changes first element only
assert items == [['a', 'b', 'c'], ['a', 'b'], ['a', 'b']]