ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Tuple
    python/기본 2022. 4. 29. 14:36
    # Tuple 은 immutable
    # immutable 이 필요한 곳에서는 list 대신에 tuple 을 사용하자
    
    t = (1, 2, 3, 4, 1, 2)
    print(type(t))  # <class 'tuple'>
    
    # t[0] = 100  # TypeError: 'tuple' object does not support item assignment
    
    print(t[0])  # 1
    print(t[1:3])  # (2, 3)
    print(t.count(1))  # 2
    
    t = ([1, 2, 3], [4, 5, 6])
    print(t[0][0])  # 1
    t[0][0] = 100
    print(t)  # ([100, 2, 3], [4, 5, 6])
    
    ####################################################################
    num_tuple = (10, 20)
    x, y = num_tuple
    print(x, y)  # 10 20
    x, y = (10, 20)
    x, y = 10, 20  # 괄호 없이 사용해도 tuple 로 인식함
    
    i = 100
    j = 200
    i, j = j, i
    print(i, j)  # 200, 100
    
    
    ####################################################################
    # unpack tuple
    items = (0, 'b', 'one', 'zero')
    
    a, *b, c = items
    print(b)  # ['b', 'one']
    
    *_, a, b = items
    print(a)  # one

    'python > 기본' 카테고리의 다른 글

    Set  (0) 2022.04.29
    Dictionary  (0) 2022.04.29
    List  (0) 2022.04.29
    String  (0) 2022.04.24
    변수, 수치, print 출력  (0) 2022.04.24

    댓글

Designed by Tistory.