Explain why creating a list of several instances of one element using something like my_list = [a] * 5 can result in strange behaviour

A good example for this would be>>> a = [0]>>> l = [a] * 5>>> l[[0], [0], [0], [0], [0]]>>> l[0][0] = 1>>> l[[1], [1], [1], [1], [1]]
You can see how creating a list of lists using multiplication results in the same object being passed rather than being cloned. This means that anytime any one element is changed in the lists, all elements change. Having a set to 0 (a single integer, instead of a list with a single integer), would work fine: that is because python copies integers differently than lists. This can get confusing, so you should always avoid statements like [a] * 5.

GM

Related Python Mentoring answers

All answers ▸

[Student query] Why do we import libraries/modules such as Numpy and Matplotlib into Python?


Whats is the difference between a function and a procedure?


Create an rock, paper, scissors game. The user should input one option, and the computer should play randomly.


Write a Python script to take a product name as input and then automatically google search reviews for it and open the top 3 search results in different tabs