Python: Careful with equal sign

December 8th, 2007 mysurface Posted in python | Hits: 68141 | 6 Comments »

To store data, object reference to a variable is very easy in python. For example, to assign an integer 5 to a

a=5

Same thing goes to string

str="hello world"

Assign data to a data structured variable, let say list,

L=[1,2,3,4,5]

Even assign a function to a variable.

import sys
wstderr=sys.stderr.write
wstderr("hello world\n")

Observed that all of them uses equal sign, but CAREFUL! Sometimes, they doesn’t work the same way as you expect them to.


In python, some variables are immutable and some are not. For example, string and tuple are immutable, but list and dictionary accept dynamic changes.

Lets look at string in python

>>> str="my snake bites"
>>> str[4]
'n'
>>> str[4]='f'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

You can’t cannot change value of a particular character in string, they are immutable. The value “my snake bites” is actually store in a new blocks of memory and str will be refers to that particular blocks of memory.

When you do this:

str2=str

The content of str is copied to str2, both of them are independent.

Lets look at list now, you are allow to delete or append data dynamically during runtime.

L=[1,2,3,4,5]

IMPORTANT: The value will be stored into a range of memory blocks, and what if you do this?

L2=L

It make L2 refers to the same memory blocks where L points to. Let see!

>>> L=[1,2,3,4,5]
>>> L2=L
>>> L2.append(6)
>>> print L
[1, 2, 3, 4, 5, 6]

Append values to L2 reflects to L too, they are refers to the same blocks of memory.

OMG! what if I wanna COPY the value from L to L2?

>>> L2=L[0:]
>>> print L2
[1, 2, 3, 4, 5, 6]
>>> L2.append(7)
>>> print L
[1, 2, 3, 4, 5, 6]
>>> print L2
[1, 2, 3, 4, 5, 6, 7]

How about dictionary?
You can use copy() method for that.

>>> D=dict()
>>> D[1]=10
>>> D[2]=20
>>> print D
{1: 10, 2: 20}
>>> D2=D.copy()
>>> print D2
{1: 10, 2: 20}
>>> D2[3]=30
>>> print D2
{1: 10, 2: 20, 3: 30}
>>> print D
{1: 10, 2: 20}

Although all of them uses equal sign, but they act differently, so bare in mind while dive in python.

6 Responses to “Python: Careful with equal sign”

  1. I suppose you mean a str[4] does not accept assignment.

    By replacing str[4]=f with str[4]='f', python interpreter will throw an assignment-not-support error, e.g. TypeError: 'str' object does not support item assignment.

    I guess it’s probably a typo. 8-)

  2. Toydi: Thanks, its a typo.

  3. Miguel Garcia Says:

    Hi,

    I may not have understood something. You said that when str is a string, the efect of the instruction str2=str is that:
    “The content of str is copied to str2, both of them are independent”.

    Is it really like this? I was pretty convinced that str2 would store a reference to the same string, so that there would not exist two copies of the string, but one. After all, since strings are immutable there is no danger in that. Wouldn’t it be a waste to build such copies of immutable objects?

    Thank you and best regards,

    Miguel

  4. Hi Miguel:
    If str and str2 are pointing to the same blocks of memory, below is the case will happen:

    str=”Hello”
    str2=str
    str2=”World”

    Then str will become “World” as well, but that is not the case.

    Maybe at the moment we do str=str2, they are pointing to the same memory, but when i do str2=”World”, str2 will spawn a new memory block. I think this will be the case.

    I think you are right at this point, thanks.

  5. ??-??. ?????????.std::string str = “Text” + c;? ??? ??? ??????? ?????? ? ????????? ????, ??? ?????????? ??? ????????.1) ?????????? ??????????? ???? ? ????????????string = const char* + char2) ??? ???????? ?????? ??? ???????????? ?????? ??????? ? ??? ????? ?????? operator+ ??? ??????????? ???? const char*…? ?????? ????? ?? ??????? ?????????? ??????????? ? ??????? ?????? ???? std::string.??? ?? ?????? ????????????, ????????????? C++, ???. ??? ??????????? ???-??????? ????????? ? ?????: ?????????? ???????? ???????????? ?? ???????????? ?????, ? ????? ?????????. ? ?????-?? :)????????:#include int main (){ { //???????? ??????? char c = ’0′; std::string str = “Text” + c; std::cout << str << std::endl; } { //??????????? ??? char c = '0'; std::string str = "Text"; str += c; std::cout << str << std::endl; } { //?? ????? ? ??? char c = '0'; std::string str = std::string("Text") + c; std::cout << str << std::endl; } rtuern 0;}

  6. hospital time spakujmy najlepiej w twardych skrzynkach czy szufladach.\r\n\r\n\r\n\r\nWszystkie gatunki art agd i rtv powinny by? zapakowane \r\n\r\nw oryginalne opakowanie| je?eli kiedy je posiadamy| w przeciwnym wypadku zawin?? w koce \r\n\r\norazzabezpieczy?|zafoliowa?} foli? b?belkow? oraz foli? typu strecz je?li to mo?liwe.Wówczas przeprowadzka tego mienia oraz transport owego sprz?tu \r\n\r\njest tylko i wy??cznie na odpowiedzialno?? w?a?ciciela .\r\n\r\n\r\n\r\nWszystkie ro?liny musz? wyl?dowa? w kontenerkach.Je?eli \r\n\r\nz?oto| oszcz?dno?ci i osobiste dokumenty s? pakowane oddzielnie i transportowane przez klienta osobi?cie do swojego domu\r\n\r\n.Planuj?c przeprowadzki pozna? wybierz czas poza szczytami \r\n\r\nwtedy sprawniej potrwa przejazd.Wszystko co powinno by? dost?pne bezpo?rednio \r\n\r\npo przybyciu do nowego mieszkanianp: jak art.higieniczne| spanie| ubrania|?ywno??| itp.\r\n\r\nmusz? by? pakowane osobno aby szybko je znale??\r\n\r\nRzeczy| takie jak ?atwopalne| toksyczne| |kwasowe itp.\r\n\r\nnie s? dozwolone.\r\n\r\nArtyku?y spo?ywcze|Spo?ywka|Jedzenie} w ostatnim dniu.Warto {posegregowa?|uprz?tn??| prowiant| które straci?y swoj? warto?? czy termin przydatno?ci|{reszt?|pozosta?o?? umie?ci? w plastikowe torby przed \r\n\r\nzapakowaniem w skrzynkach.\r\n\r\nMeble-pó?ki powinny by? wyci?gni?te ca?kowicie i zabezpieczy? wierzcho?ki mebli (np.\r\n\r\nSzafy| pó?ki i przek?adki). Miej tak?e na uwadze| aby zebra? wszystkie ?ruby + narz?dzia do przeprowadzki pozna? .\r\n\r\nNa miejscu mo?liwe b?dzie szybko zamra?arki

Leave a Reply