Beginner's confusion

This is the place for queries that don't fit in any of the other categories.

Beginner's confusion

I am a newcomer to Python (3.2) and am clearly missing something basic here: I defined

Code: Select all
`a = [ [1, [2,3,4]] , [2, [7,8,9]] ]`

Then I set
Code: Select all
`a[0][0] = 37`

expecting to get
Code: Select all
`a = [ [37, [2,3,4]] , [2, [7,8,9]] ]`

Code: Select all
`a = [ [37, [2,3,4]] , [37, [7,8,9]] ]`

What am I doing wrong?

Thanks
Last edited by Mekire on Tue Oct 08, 2013 12:29 am, edited 1 time in total.
Reason: First post lock
ldworsky

Posts: 3
Joined: Mon Oct 07, 2013 7:26 pm

Re: Beginner's confusion

Hi mate. I've just tried your code and it works exactly how you first expected it to
dboxall123

Posts: 122
Joined: Fri Jul 12, 2013 5:28 pm

Re: Beginner's confusion

Code: Select all
`c = [[0, []]]*5c[2][0] = 13print (c)`

I get

Code: Select all
`[[13, []], [13, []], [13, []], [13, []], [13, []]]`

but I thought I'd get

Code: Select all
`[[0, []], [0, []], [13, []], [0, []], [0, []]]`

Thanks,

Larry
ldworsky

Posts: 3
Joined: Mon Oct 07, 2013 7:26 pm

Re: Beginner's confusion

Code: Select all
`#c = [[0, []]] * 5d = [[0, []] for i in range(5)]d[2][0] = 13print(d)"""Output-->[[0, []], [0, []], [13, []], [0, []], [0, []]]"""`

Let`s look at list c and d.
Code: Select all
`>>> c[[0, []], [0, []], [0, []], [0, []], [0, []]]>>> d[[0, []], [0, []], [0, []], [0, []], [0, []]]`

Hmm look the same?
Code: Select all
`>>> id(c[0])44290296>>> id(c[1])44290296>>> id(c[2])44290296>>> id(d[0])44342528>>> id(d[1])44267640>>> id(d[2])44294312>>> help(id)Help on built-in function id in module __builtin__:id(...)    id(object) -> integer        Return the identity of an object.  This is guaranteed to be unique among    simultaneously existing objects.  (Hint: it's the object's memory address.)>>> `

In list c all list point to the same place in memory.
In list d all list point to a unique place in memory.
http://www.precheur.org/python/copy_list
http://python.net/~goodger/projects/pyc ... -variables
We will be moving to python-forum.io on October 1 2016

snippsat

Posts: 1251
Joined: Thu Feb 21, 2013 12:04 am

Re: Beginner's confusion

Many thanks - This is absolutely the correct answer.
ldworsky

Posts: 3
Joined: Mon Oct 07, 2013 7:26 pm

Re: Beginner's confusion

ldworsky wrote:Many thanks - This is absolutely the correct answer.

Very good question too. Understanding how Python handles referencing objects is really important. Getting it straight now will save you all kinds of headaches later.

Marbelous

Posts: 401
Joined: Fri May 31, 2013 8:12 pm