ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด/Python

ํŒŒ์ด์ฌ ๊นŠ์€ ๋ณต์‚ฌ์™€ ์–•์€ ๋ณต์‚ฌ

์„œ์•„๋ž‘๐Ÿ˜ 2024. 4. 29. 01:33

 

 

๊ฐ์ฒด ์ฐธ์กฐ ํ™•์ธ

r1 = [1,2,3]
r2 = r1
r1 is r2    # True(r1๊ณผ r2๊ฐ€ ์ฐธ์กฐํ•˜๋Š” ๊ฐ์ฒด๋Š” ๋™์ผํ•œ๊ฐ€?)
r1 == r2    # True(r1๊ณผ r2์˜ ๊ฐ’์ด ๊ฐ™์€๊ฐ€?)

r1 = [1,2,3]
r2 = list(r1)
r1 is r2    # False(r1๊ณผ r2๊ฐ€ ์ฐธ์กฐํ•˜๋Š” ๊ฐ์ฒด๋Š” ๋™์ผํ•œ๊ฐ€?)
r1 == r2    # True(r1๊ณผ r2์˜ ๊ฐ’์ด ๊ฐ™์€๊ฐ€?)

์–•์€ ๋ณต์‚ฌ์˜ ๋ฌธ์ œ์ ์„ ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

r1 = ['John', ('man', 'USA'), [175, 23]]
r2 = list(r1)

r2[2][1] += 1   # John์˜ ๋‚˜์ด ํ•œ์‚ด ๋” ๋จน์Œ
print(r1)
print(r2)

# ['John', ('man', 'USA'), [175, 24]]
# ['John', ('man', 'USA'), [175, 24]]

r2๋งŒ ๋ณ€๊ฒฝ๋˜๊ธธ ์›ํ–ˆ์œผ๋‚˜ r1์˜ ๋ ˆํผ๋Ÿฐ์Šค๊นŒ์ง€ ๊ฐ™์ด ๋ณต์‚ฌ๋˜๋ฉด์„œ r1์˜ ๋ฆฌ์ŠคํŠธ์™€ r2์˜ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๊ฐ™์€ ๊ฐ์ฒด๋ฅผ ๋ฐ”๋ผ๋ณด๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๊นŠ์€ ๋ณต์‚ฌ๋ฅผ ์ง„ํ–‰ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

์œ„ ๋‚ด์šฉ ๊ธฐ๋ฐ˜์œผ๋กœ ๊นŠ์€ ๋ณต์‚ฌ๋ฅผ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

from copy import deepcopy
r1 = ['John', ('man', 'USA'), [175, 23]]
r2 =  deepcopy(r1)

r2[2][1] += 1   # John์˜ ๋‚˜์ด ํ•œ์‚ด ๋” ๋จน์Œ
print(r1)
print(r2)

# ['John', ('man', 'USA'), [175, 23]]
# ['John', ('man', 'USA'), [175, 24]]

๋ฌธ์ž์—ด, ํŠœํ”Œ, int, float๊ณผ ๊ฐ™์€ Immutable ๊ฐ์ฒด์— ๋Œ€ํ•ด์„œ๋„ ์–•์€ ๋ณต์‚ฌ๋Š” ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์›๋ณธ ๊ฐ์ฒด์˜ ๋ณ€ํ•จ์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— ์–•์€ ๋ณต์‚ฌ๋กœ ๋ฐœ์ƒํ• ๋งŒํ•œ ๋ฌธ์ œ๋Š” ์ƒ๊ธฐ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋ฆฌ์ŠคํŠธ์™€ ๋”•์…”๋„ˆ๋ฆฌ ๊ฐ™์ด ์›๋ณธ ๊ฐ์ฒด๊ฐ€ ๋งˆ๊ตฌ ๋ฐ”๋€Œ๋Š” Mutable ๊ฐ์ฒด๋ฅผ ๋ณต์‚ฌํ•  ๋•Œ๋Š” ๊นŠ์€ ๋ณต์‚ฌ๋ฅผ ํ•ด์ค์‹œ๋‹ค!