10 подписчиков
📑 Copying Lists
📑 Task
1) What will the program print?
2) Make a list of identical elements and copy this list
so that the result of the last three lines looks different:
[[1], [], []] [[2], [], []]
list_ = 3 * [[]]
list_copy = list_.copy()
print(list_, list_copy)
list_[0].append(1)
list_copy[0].append(2)
print(list_, list_copy)
📑 Answer
1) 2 lists of empty lists: [[], [], []] [[], [], []]
2 identical lists of elements: [[1, 2], [1, 2], [1, 2]] [[1, 2], [1, 2], [1, 2]]
2)
list_ = []
[list_.append([]) for _ in range(3)]
list_copy = [_[:] for _ in list_]
print(list_, list_copy)
list_[0].append(1)
list_copy[0].append(2)
print(list_, list_copy)
Около минуты
23 апреля 2024