카테고리 없음

[Python] Mutable, Immutable

운덩하는 개발자 2023. 9. 15.
반응형

결론 요약

Mutable Immutable
객체 생성 후, 상태 수정 가능 (메모리 주소 유지) 객체 생성 후, 상태 수정 불가 (메모리 주소 바뀜)
스레드로부터 안전하지 않다 스레드로부터 안전
list

set

dicitionary
numbers ( int, float, rational, decimal, complex & boolean)

str

tuple

frozen set

Immutable 예제 코드

# Immutalbe 예제
print("="*30)
print("     Immutable Int 예제")
print("="*30)
num1 = 1
num2 = 1
num3 = 1

print(f"num1 : {num1}, 주소 : {id(num1)}")
print(f"num2 : {num2}, 주소 : {id(num2)}")
print(f"num3 : {num3}, 주소 : {id(num3)}")

# 값 변경
num1 += 1
num2 += 2
num3 += 1

print(" -----------값 변경-----------")
print(f"num1 : {num1}, 주소 : {id(num1)}")
print(f"num2 : {num2}, 주소 : {id(num2)}")
print(f"num3 : {num3}, 주소 : {id(num3)}")
print()
print()
print()
print("="*30)
print("      Immutable str 예제")
print("="*30)
str1 = "abc"
str2 = "abc"
str3 = "abc"

print(f"str1 : {str1}, 주소 : {id(str1)}")
print(f"str2 : {str2}, 주소 : {id(str2)}")
print(f"str3 : {str3}, 주소 : {id(str3)}")

print(" -----------값 변경-----------")
str1 = str1.replace("a", "c")
str2 = "cbc"
str3 = str3.upper() # 대문자로 변경

print(f"str1 : {str1}, 주소 : {id(str1)}")
print(f"str2 : {str2}, 주소 : {id(str2)}")
print(f"str3 : {str3}, 주소 : {id(str3)}")

출력 결과

Python Immutable 예제

Immutable 예제 설명 (문자열 풀링)

 Int와 str는 Immutable(불변) 자료형입니다. 한 번 생성된 Int 객체의 값은 변경할 수 없어, 값을 변경하려면 새로운 Int 객체를 생성하고 해당 변수를 업데이트해야 합니다. 이로 인해 같은 값을 가지는 Int변수들이 같은 주소를 가지게 됩니다.

다만, Python에서는 작은 정수 및 일부 문자열을 캐시하는 문자열 풀링 기능을 사용하는데, 문자열 풀링 기능은  작은 정수 및 일부 작은 문자열은 미리 생성되어 캐시에 저장하는 것인데, 해당 기능을 통해 같은 값을 가지는 변수는 동일한 객체를 잠조할 수 있으며 이로 인해, 작은 숫자나 공통 문자열을 여러 번 사용할 때 메모리를 절약할 수 있습니다.

예를 들어, "abc"와 같은 간단한 문자열은 문자열 풀링에 의해 시되므로 같은 값을 가지는 변수는 동일한 주소를 가질 수 있습니다. 그러나 문자열이 변경되면(Replace, 대문자 변경 등), 새로운 문자열 객체가 생성되고 새로운 주소를 가지게 됩니다.

Mutable 예제 코드

# Mutalbe 예제
print("="*30)
print("     Mutable List 예제")
print("="*30)
arr1 = ['a', 'b', 1]
arr2 = ['a', 'b', 1]
arr3 = ['a', 'b', 1]

print(f"arr1 : {arr1}, 주소 : {id(arr1)}")
print(f"arr2 : {arr2}, 주소 : {id(arr2)}")
print(f"arr3 : {arr3}, 주소 : {id(arr3)}")

# 값 변경
arr1.append(2) # ['a', 'b', 1, 2]
arr2.append(2) # ['a', 'b', 1, 2]


print(" -----------값 추가-----------")
print(f"arr1 : {arr1}, 주소 : {id(arr1)}")
print(f"arr2 : {arr2}, 주소 : {id(arr2)}")
print(f"arr3 : {arr3}, 주소 : {id(arr3)}")
print()
print("="*30)
print("     Mutable Dictionary 예제")
print("="*30)
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 1, 'b': 2, 'c': 3}
d3 = {'a': 1, 'b': 2, 'c': 3}

print(f"d1 : {d1}, 주소 : {id(d1)}")
print(f"d2 : {d2}, 주소 : {id(d2)}")
print(f"d3 : {d3}, 주소 : {id(d3)}")

print(" -----------값 변경-----------")
d1['a'] = 11
d2['d'] = 22

print(f"d1 : {d1}, 주소 : {id(d1)}")
print(f"d2 : {d2}, 주소 : {id(d2)}")
print(f"d3 : {d3}, 주소 : {id(d3)}")

 

출력 결과

Python mutable 예제

Mutable 예제 설명

 메모리에 각각 값들이 생성되고 참조를 하기에 주소가 다르며, Immutable와는 다르게 해당 객체의 값을 변경할 수 있어,  내부의 값이 변경된다고 해도, 새로운 객체를 만들 필요 없이 동일한 객체를 계속 참조하게 됩니다.

스레드 안정성

 Mutable유형의 데이터가 스레드로부터 안전하지 않은 이유는 데이터의 상태가 변결될 수 있기에, 여러 스레드가 동시에 해당 데이터를 수정하려고 시도하면 데이터 무결성 문제 발생 가능합니다. 이러한 데이터 유형을 스레드로부터 안전하게 사용하려면 락(lock)과 같은 명시적인 스레드 동기화 메커니즘을 사용해야 하며,  Immutable유형의 데이터는 값을 변경할 수 없기에 무결성을 보존하기 위한 별도의 동기화가 필요하지 않아. 이는 스레드로부터 안전한 특성을 제공합니다.

Reference

https://a-littlecoding.tistory.com/87

 

[Python] Mutable, Immutable한 자료구조에 대해 공부해보자

📚 파이썬의 Mutable, Immutable 📒 Mutable Mutable Definition Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a c

a-littlecoding.tistory.com

https://blockdmask.tistory.com/570

 

[python] 파이썬 mutable, immutable 객체에 관해서

안녕하세요. BlockDMask입니다. 오늘은 파이썬에 있는 mutable 객체, immutable 객체에 대한 차이점에 대해서 알아보겠습니다. 1. 파이썬 mutable, immutable 설명 2. 파이썬 mutable, immutable 값이 변경될 때 에제

blockdmask.tistory.com

 

반응형

댓글