파이썬/파이썬(python) 초급

list is mutable, tuple is immutable, list aliasing, list(), clone by value

Olivia-BlackCherry 2023. 5. 1. 04:52

목차

    우선 mutable은 변할 수 있는, immutable 수정할 수 없는, 변할 수 없다는 뜻을 가진다. 

    파이썬에서 비슷한 모습을 하고 있는 타입이 list와 tuple이다.

    list는 mutable하고, tuple은 immutable하다. 

    그래서 메소드를 쓸 때 차이점이 있는데 이를 살펴보도록 하자. 

     

    1. 인덱스값 변경 불가!

    # create a list and a tuple containing the same elements
    my_list = [1, 2, 3]
    my_tuple = (1, 2, 3)
    
    # modify the first element of the list
    my_list[0] = 4
    print(my_list)   # Output: [4, 2, 3]
    
    # try to modify the first element of the tuple (this will cause an error)
    # my_tuple[0] = 4  # TypeError: 'tuple' object does not support item assignment

    위의 예제를 보자. 

    my_list의 타입은 리스트, my_tuple의 타입은 튜플이다. 

    리스트에서는 인덱스에 접근하여 그 값을 바꿀 수 있다. 

    하지만 튜플은 불가능하다. 

     

    튜플의 원소를 바꾸는 것은 불가능하기에, 차라리 새로운 튜플을 만들어야 한다. 

    # create a new tuple with the first element changed
    my_new_tuple = (4,) + my_tuple[1:]
    print(my_new_tuple)   # Output: (4, 2, 3)

     

     

    2. 메소드

    # create a list and a tuple containing the same elements
    my_list = [3, 1, 4, 1, 5, 9, 2]
    my_tuple = (3, 1, 4, 1, 5, 9, 2)
    
    # sort the list and tuple using their respective methods
    my_list.sort()
    # my_tuple.sort()  # AttributeError: 'tuple' object has no attribute 'sort'
    
    # print the sorted list and tuple
    print(my_list)   # Output: [1, 1, 2, 3, 4, 5, 9]
    print(my_tuple)  # Output: (3, 1, 4, 1, 5, 9, 2)

    위의 예제에서 my_list에 sort()메소드를 쓴다면

     my_list를 새로 정의하지 않아도, my_list는 mutable하기 때문에 my_list가 sort()되어져버린다. 

     

    한편, 튜플은 mutable하기 때문에 새롭게 정의해야 한다. 

    또한 튜플은 sort()메서드가 없기 때문에 sorted()함수를 쓴다.

    # create a new sorted tuple from the original tuple
    my_sorted_tuple = tuple(sorted(my_tuple))
    print(my_sorted_tuple)   # Output: (1, 1, 2, 3, 4, 5, 9)

     

     

    3. list aliasing: copy by reference

    alias는 별칭, 별명을 뜻한다. 

    python에서 alias는 변수가 같은 객체를 참조하는 것이다. 

    리스트에는 매우 중요한 개념이다.

    list1 = [1, 2, 3]
    list2 = list1

    위의 예제에서는 list2와 list1은 동일한 객체를 참조한다.

    reference 참조

    다시 말해, list2와 list1은 같은 리스트를 참조하기 때문에, 

    list1을 변경하면 lsit2도 변경된다. 

    list1 = [1, 2, 3]
    list2 = list1
    
    list1.append(4)
    print(list1)  # Output: [1, 2, 3, 4]
    print(list2)  # Output: [1, 2, 3, 4]

    따라서 리스트의 aliasing을 사용할 때는 주의해야 한다. 

     

     

    4. 리스트 복사: clone by value

    만약 두 개의 다른 리스트를 만들고 싶다면 aliasing을 하지 않고 '복사'를 해야한다.

    리스트복사는 리스트의 새로운 인스턴스를 만드는 것으로, 복사한 리스트와 원본 리스트는 독립적이다. 

    list1 = [1, 2, 3]
    list2 = list1[:]  # 리스트를 슬라이싱하여 복사합니다.
    
    list1.append(4)
    print(list1)  # Output: [1, 2, 3, 4]
    print(list2)  # Output: [1, 2, 3]

    list1과 list2는 동일한 원소를 가지고 있지만, 독립적이다. 

    서로에게 영향을 주지 않는다. 

     

    리스트를 복사하는 방법은 list() 함수를 써도 된다. 

    list1 = [1, 2, 3]
    list2 = list(list1)  # 리스트를 복사합니다.
    
    list1.append(4)
    print(list1)  # Output: [1, 2, 3, 4]
    print(list2)  # Output: [1, 2, 3]