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
Answered by Gustas M. Python tutor

1329 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What is Object-Oriented Programming?


Explain how you would write a python program that takes a rectangle and a point in a 2D space as command-line arguments and checks if they intersect.


What are docstrings and how do I use them to improve my code readability?


Write a function that takes a string, and outputs that string formatted in camelcase. (alternating upper and lower case for each character, e.g. cAmElCaSe)


We're here to help

contact us iconContact ustelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences