Basic Python

copy, copy.copy, copy.deepcopy, get, next, id

Naranjito 2021. 5. 4. 17:27
  • copy

Under the same object, one can change one copy without changing the other. Therefore, if one of them changed, the other one will be changed affected by changed one.

a = [1, 2, 3, 4]
b = a     # shallow copy
print(b)    # [1, 2, 3, 4]
b[2] = 100   
print(b)    # [1, 2, 100, 4]
print(a)    # [1, 2, 100, 4]

 

  • copy.copy

Shallow copy, once copy from one to another one, its reference is same object. Copy only the shell.

import copy

a = [1, [1, 2, 3]]
b = copy.copy(a)    # shallow copy 
print(b)    # [1, [1, 2, 3]] 
b[0] = 100
print(b)    # [100, [1, 2, 3]] 
print(a)    # [1, [1, 2, 3]] shallow copy 

c = copy.copy(a)
c[1].append(4)   
print(c)    # [1, [1, 2, 3, 4]] 
print(a)    # [1, [1, 2, 3, 4]] #a and c has same object reference

 

  • copy.deepcopy 

Copies the object then recursively inserts copies into the objects. It copies deeply. Object of copy isn't affected by subject.

import copy

a = [1, [1, 2, 3]]
b = copy.deepcopy(a)    
print(b)    # [1, [1, 2, 3]] 
b[0] = 100
b[1].append(4)
print(b)    # [100, [1, 2, 3, 4]] 
print(a)    # [1, [1, 2, 3]] didn't changed, didn't affected by b

 

  • get

Get the valud of the item in Dictiionary.

car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

x=car.get('model')
x
>>>
Mustang

 

  • next

It returns the next value for the iterable.

iterable_value='Iter'
iterable_obj=iter(iterable_value)

while True:
  try:
    item=next(iterable_obj)
    print(item)
  except StopIteration:
    break  
>>>
I
t
e
r

 

  • id

Identity, it returns identity of an object.