파이썬 기초 Mutable vs Immutable Objects

Parker cho·2021년 7월 10일
2

파이썬 정복

목록 보기
1/2
post-thumbnail

개요

파이썬의 모든 데이터는 객체 혹은 객체 간의 관계로 표현됩니다. 모든 객체는 Identity, Type, Value를 가지고 있습니다.

Identity

특정 객체의 identity 는 선언된 이후 변하지 않습니다. 이는 메모리에 있는 주소 라고 생각할 수 있습니다.
파이썬의 is Operator는 두 객체의 Identity를 비교합니다. python built-in function 인 in() 함수를 사용하여 특정 객체의 Identity를 확인 할 수 있습니다.

a = 5
print(id(a))

출력

94252923837056


Type

객체의 타입은 할당이 가능한 값과 연산을 정의합니다. (예시. 객체의 Length를 구할 수 있는가?)
python built-in function인 type() 함수로 객체의 타입을 확인 할 수 있습니다.

a = 1
b = 1.0
c = 1 - 1j

print(type(a))
print(type(b))
print(type(c))

출력

<class 'int'>
<class 'float'>
<class 'complex'>


Value

특정 객체의 값은 변할 수 있습니다. 값이 변할 수 있는 객체는 mutable 변할 수 없는 객체는 immutable이라 명합니다.

❗️중요

특정 객체는 다른 객체를 포함하고 있습니다. 이러한 객체를 container 객체라 명합니다.
예시로 tuple, dictionary, list 들이 존재합니다.

파이썬에서의 Mutable, Immutable 데이터 타입들

Mutable 데이터 타입

  • 사용자 정의 객체
  • list
  • dictionary
  • set

Immutable 데이터 타입

  • int
  • float
  • demical
  • bool
  • string
  • tuple
  • range

List vs Tuple

Indexing Example

list_example = [1,2,3]
tuple_example = (1,2,3)

print(list_example[0])
print(tuple_example[0])

출력

1
1


Changing Value Example

list_example = [1,2,3]
tuple_example = (1,2,3)

list_example[0] = 3
print(list_example)

tuple_example[0] = 3
print(tuple_example)

출력
[3,2,3]
TypeError Traceback (most recent call last)
5 print(list_example)
6
----> 7 tuple_example[0] = 3
8 print(tuple_example)

TypeError: 'tuple' object does not support item assignment


list 에서는 출력이 잘되는 반면 tuple은 에러가 발생하는 것을 알 수 있습니다.

Expanding Example

list_example = [1,2,3]
tuple_example = (1,2,3)

print("list before = ", id(list_example))
print("tuple before = ", id(tuple_example))

list_example += list_example
tuple_example += tuple_example

print("list after = ", id(list_example))
print("tuple after = ", id(tuple_example))

출력

list before = 139670178338128
tuple before = 139670246777632
list after = 139670178338128
tuple after = 139670178088784


list 는 identity 가 달라지지 않은 반면 tuple은 달라진 것을 확인할 수 있습니다. 이는 list는 메모리에 있는 값은 변경한 반면 tuple은 새로운 tuple 객체를 생성한 것을 알 수 있습니다.

위의 결과로 list 가 tuple 보다 메모리 관리 측면에서 효율적인 것을 알 수 있습니다.

Other Immutable Data Type Examples

tuple 이 아닌 다른 immutable object 에 대한 예시도 함께 살펴보겠습니다.

int

test_num = 42
print(id(test_num))
test_num = 43
print(id(test_num))

출력

94252923838240
94252923838272


identity의 값이 다르게 나오는 것을 확인 할 수 있습니다. 위의 결과로 immutable 객체는 한번 초기화 되면 값을 변경할 수 없음을 알 수 있습니다.

다른 immutable 데이터 타입에서의 결과도 함께 보겠습니다.

string

test_str = "hello test"
print(id(test_str))
test_str = "hello world"
print(id(test_str))

출력

139670178329584
139670178789872


Copying Mutable Objects by Reference

mutable 데이터 타입에서의 참조에 의한 복사 예시부터 살펴보겠습니다.

mutable data copy

values = [1,2,3,4]
values2 = values

print(id(values))
print(id(values2))


values.append(1)

print(values is values2)

print(values)
print(values2)

출력

139670179112032
139670179112032
True
[1, 2, 3, 4, 1]
[1, 2, 3, 4, 1]


위의 결과로 mutable한 데이터는 동일한 객체의 주소를 가리키고 있는 것을 알 수 있습니다.

immutable data copy

text = "kotlin"
text2 = text
print(id(text))
print(id(text2))
print()
text += " python "
print(id(text))
print(id(text2))
print(text is text2)
print()
print(text)
print(text2)

출력

139670842899312
139670842899312

139670179153648
139670842899312
False

kotlin python
kotlin


위의 결과로 immutable 데이터에서는 값을 변경하면 서로 다른 주소를 가리키고 있는 것을 알 수 있습니다.

The == operator

identity 비교가아닌 값의 비교를 하고 싶을때는 == 연산자를 사용해야합니다.

num1 = [1,2,3,4,5]
num2 = [1,2,3,4,5]

print(num1 == num2)
print(num1 is num2)

출력

True
False


Immutable Object Changing Its Value

immutable 한 객체여도 포함하고 있는 객체가 mutable 하고 포함하고 있는 객체의 값 변경 자체가 일어나면 immutable 안에 있는 객체의 값의 변경이 가능합니다.

score = [23,42,32]

user = ('myungki', score)

print(type(user))
print(user)
score[0] = 100
print(user)

출력

<class 'tuple'>
('myungki', [23, 42, 32])
('myungki', [100, 42, 32])


❓기억합시다

위의 예시에서 user 의 값의 변경이 일어난다 하더라도 user는 immutable 한 객체로 취급됩니다.

위의 예시와는 다르게 immutable container 안의 객체도 immutable 할 경우 값의 변경이 불가능합니다.

score = (23,42,13)

user = ('myungki', score)
print(id(user))
print(user)

score += (13,24)

print(id(user))
print(user)

출력

139670178224800
('myungki', (23, 42, 13))
139670178224800
('myungki', (23, 42, 13))


🌙 마치며..

이 문서는 https://towardsdatascience.com/https-towardsdatascience-com-python-basics-mutable-vs-immutable-objects-829a0cb1530a 의 내용을 번역한 문서입니다. 오역이나 오타 지적해주시면 감사하겠습니다 ㅎㅎ

profile
true nobility is being superior to your former self

2개의 댓글

comment-user-thumbnail
2022년 1월 24일

글 잘 읽었습니다! 오타를 발견해서 알려드려요 Value 설명 파트의 "값이 변할 수 있는 객체는 mutable 변할 수 있는 객체는 immutable이라 명합니다." 부분에 오타가 있는 것 같아요.
긴 글 번역하시느라 고생 많으셨습니다. 감사합니다 :)

1개의 답글