Python list of lists, changes reflected across sublists unexpectedly

Answer

When you write [x]*3 you get, essentially, the list [x, x, x]. That is, a list with 3 references to x. When you then change x all three references are changed.

To fix it, you need to make sure that you create a new list at each position. One way to do it is

[[1]*4for n in range(3)]

All python Questions

Ask your interview questions on python

Write Your comment or Questions if you want the answers on python from python Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---