Changing a Value in List of lists

Rishabh Dixit rishabhdixit11 at gmail.com
Sun Sep 2 07:00:28 EDT 2012


Hi Chris,

Thanks for your reply. I tried this -

>>> ls=[0 for i in range(5)]
>>> mat=[ls for i in range(5)]
>>> mat[1][2]+=1
>>> mat
[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0,
1, 0, 0]]

I guess here also the same issue is there as ls refers to one list that is
being repeated through mat and change in one causes change in others also.

Is there any solution to change all elements independently.


On Sun, Sep 2, 2012 at 3:14 PM, Rishabh Dixit <rishabhdixit11 at gmail.com>wrote:

>
> Hi all,
>
> I have a doubt regarding how the list work in following case-
>
> >>> ls=[[0]*5]*5
> >>> ls[1][1]+=1
> >>> ls
> [[0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0,
> 1, 0, 0, 0]]
>
>
> Here, according to me only one value in ls should be incremented but it is
> increasing 1 value in all the lists of ls. Why??
> --
> Regards,
> Rishabh Dixit
> MSc.(Tech) Information Systems,
> BITS Pilani
>
>


-- 
Regards,
Rishabh Dixit
MSc.(Tech) Information Systems,
BITS Pilani
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120902/c15ef6b2/attachment.html>


More information about the Python-list mailing list