Jump to content

Unclear about list assignment in python


Dagl1

Recommended Posts

Hi,
I have recently started going through a python textbook and in one of the exercises I find myself not really understanding why the code does what it does. 
The reason why the 0+1 is there, is that in the actual program those will be the iterable (i) in a loop. 
The code should swap two values in a list , I guess that itself can be done more simply than this code, but I will search/figure that part out myself.
I am most interested in the behaviour of the following Python 3.8.1 code (I added comments with what I THINK should/would happen).

List = [5,1,2,3,4]
TempList = List # Set Templist equal to List
print(List[0])  # Returns 5

TempList[0] = List[0+1]  #replace first element in TempList with second element of List
TempList[0+1] = List[0] #replace second element of TempList with first element of List
print(TempList,List) # Returns[ 1, 1, 2, 3, 4] [1, 1, 2, 3, 4]

What I don't get here is, the way I understand how variables change, is that only TempList should be different now? We only 'read' the values of List[0+1] and List[0] right? (Well obviously not, but could someone show me what I am getting wrong or referring me to a source that explains this?

I looked through this, but didn't see it (although I skimmed and did may have missed it): https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences

Thanks in advance,
Dagl

So I have found the answer, I should use:

TempList = List[:] 

But I don't really understand why.

a = 5
b = a
a +=5
print(b) # returns 5, not 10

what exactly is different when we say:
TempList = List

from:
b = a

Thanks

Edited by Dagl1
Link to comment
Share on other sites

27 minutes ago, Dagl1 said:

TempList = List

AFAIK python does not make a copy of objects so TempList and List points to the same object. Operations on TempList affects the objects and List points to the same object. 

This operation: TempList = List[:]  Creates a clone of the list so there are two independent objects in memory.


When using primitive types such as integers or booleans  python will make a copy. 

This behaveour of ”values” vs ”references” may differ from language to language.

https://docs.python.org/3/faq/programming.html#how-do-i-copy-an-object-in-python

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.