๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ | Python/ํŒŒ์ด์ฌ ๋ฌธ๋ฒ•

์–•์€ ๋ณต์‚ฌ์™€ ๊นŠ์€ ๋ณต์‚ฌ

by KASSID 2021. 9. 13.

๋ชฉ์ฐจ

    728x90

    ์–•์€ ๋ณต์‚ฌ(shallow copy)

    ๊ฐ’์„ ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋กœ ๋ณต์‚ฌํ•  ๋•Œ '์ฐธ์กฐ ๊ฐ’'๋งŒ ๋ณต์‚ฌํ•˜๋Š” ๋ฐฉ์‹

    1. copy

    import copy
    a = [1,2,3]
    b = a.copy()
    a[2] = 2
    print(a)
    print(b)
    ใ…กใ…กใ…กใ…กใ…กใ…กใ…กใ…ก
    [1, 2, 2]
    [1, 2, 3]

    ๊ฐ’๋งŒ ๋ณต์‚ฌ๋ฅผ ํ•ด์˜ค๋Š” ๊ฒƒ์ด๋ฏ€๋กœ a์— ํ• ๋‹น๋œ ๊ฐ’์„ ๋ฐ”๊พธ์–ด๋„ b์˜ ๊ฐ’์€ ๋ณ€ํ™”๊ฐ€ ์—†๋‹ค!

    'b = a'๋ผ๋Š” ์ฝ”๋“œ์™€ ๋Œ€๋น„๋˜๋Š” ๋ฐฉ์‹์ด๋‹ค.

     

    2. [:]

    a = [1,2,3]
    b = a[:]
    a[2] = 2
    print(a)
    print(b)
    ใ…กใ…กใ…กใ…กใ…กใ…กใ…กใ…ก
    [1, 2, 2]
    [1, 2, 3]

    ์ธ๋ฑ์‹ฑ์„ ํ™œ์šฉํ•˜์—ฌ ์–•์€ ๋ณต์‚ฌ๋ฅผ ํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋‹ค.

     

    ์ฃผ์˜

    import copy
    a = [1,2,3,[4,5,6]]
    b = a.copy()
    a[3][0] = 2
    print(a)
    print(b)
    ใ…กใ…กใ…กใ…กใ…กใ…กใ…กใ…ก
    [1, 2, 3, [2, 5, 6]]
    [1, 2, 3, [2, 5, 6]]

    '๋ฆฌ์ŠคํŠธ ์•ˆ์˜ ๋ฆฌ์ŠคํŠธ'๋Š” copyํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ๋„ ๊ฐ’์˜ ๋ณ€๊ฒฝ์ด ์ ์šฉ๋œ๋‹ค.

     

    ๊นŠ์€ ๋ณต์‚ฌ(deep copy)

    ์ฐธ์กฐ๊ฐ’๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์ฐธ์กฐ ํ˜•์‹๊นŒ์ง€ ๋ณต์‚ฌํ•˜๋Š” ๋ฐฉ์‹, ์ „์ฒด๋ณต์‚ฌ

    import copy
    a = [1,2,3,[4,5,6]]
    b = copy.deepcopy(a)
    a[3][0] = 2
    print(a)
    print(b)
    ใ…กใ…กใ…กใ…กใ…กใ…กใ…กใ…ก
    [1, 2, 3, [2, 5, 6]]
    [1, 2, 3, [4, 5, 6]]

    ๋ฆฌ์ŠคํŠธ ์•ˆ์˜ ๋ฆฌ์ŠคํŠธ๋„ deepcopyํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜์ง€ ์•Š๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

     

    '๐Ÿ | Python > ํŒŒ์ด์ฌ ๋ฌธ๋ฒ•' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

    ํ•จ์ˆ˜_(1)  (0) 2021.09.19
    ๋ฌธ์ž์—ด ํฌ๋งคํŒ…  (0) 2021.09.18
    ๋ฎคํ„ฐ๋ธ”(mutable)๊ณผ ์ด๋ฎคํ„ฐ๋ธ”(immutable)  (0) 2021.09.13
    ๋ณ€์ˆ˜  (0) 2021.09.13
    while  (0) 2021.09.06

    ๋Œ“๊ธ€