Check for mutability in Python?

后端 未结 7 1885
小鲜肉
小鲜肉 2020-12-28 13:23

Consider this code:

a = {...} # a is an dict with arbitrary contents
b = a.copy()
  1. What role does mutability play in the keys and valu
7条回答
  •  感动是毒
    2020-12-28 13:52

    you can easily check if datatype is mutable or immutable by print an id or address of memory location of that datatype if datatype is immutable the address of memory location will change as you update the variable for example:

    stn = 'Hello'
    print(id(stn)) 
    

    you will get address of memory location of that variable stn but when you concatenate that variable with some value and then go ahead print an address of memory location you will get different output from the first one likewise

    stn += ' world'
    print(id(stn))
    

    for sure you will get another address of memory location from the first one but when you do it to mutable datatype an address of memory location will stay the same for example

    lists = [1, 2, 3]
    print(id(lists))
    

    here you will get an address of memory location and also also if you go ahead and append some numbers to that lists an address of memory location will continue to be the same

    lists.append(4)
    print(id(lists))
    

    and you have notice that an address of memory location is not the same to all computers so you couldn't check the same datatype to different computers and get same result

提交回复
热议问题