[점프투파이썬] Immutable vs Mutable

해롱그·2023년 6월 2일
0

파이썬

목록 보기
4/12
post-thumbnail

🔅 Java의 call by reference, call by value의 개념과 비슷함!

1. Immutable

변하지 않는 자료형
정수, 실수, 문자열, 튜플

a = 1
def vartest(a):
	a = a+1
vartest(a)
print(a)

>>> 1


정수는 immutable이므로 새로운 a(지역변수)를 만들고, 이는 return되지 않으므로 영향 X

2. Mutable

변할 수 있는 자료형
리스트, 딕셔너리, 집합

#리스트
b = [1, 2, 3]
def vartest(b):
    b = b.append(4)
vartest(b)
print(b)

>>> [1, 2, 3, 4]

#튜플 -> error!!
b = (1, 2, 3)
def vartest(b):
    b = b.append(4)
vartest(b)
print(b)

>>>     b = b.input(4)
	AttributeError: 'tuple' object has no attribute 'input'

profile
사랑아 컴퓨터해 ~

0개의 댓글