Jump to content

Unclear about list assignment in python

Featured Replies

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

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

  • Author

Ah okay, that makes sense, thanks!

 

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.