Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

냥집사의 개발일지

Python - 파이썬 기본 문법 정리 (tuple) 본문

Python

Python - 파이썬 기본 문법 정리 (tuple)

깅햄찌 2022. 10. 3. 16:45
반응형

안녕하세요 오늘은 가장 특별한 파이썬 자료형 중 하나인 tuple에 대해 정리해보겠습니다.  

tuple은 list와 마찬가지로 여러 자료형 요소의 sequence입니다.

다만, tuple의 요소들은 불변합니다. 

한 번 정의된 tuple의 요소들은 추가, 삭제, 수정 등을 할 수 없습니다. 

 

1. tuple 생성하기

empty_tuple1 = ()
str = ('Jeff')
tuple2 = ('Jeff',)
tuple3 = ('Jeff','Alana')

print(type(empty_tuple1))
print(type(str))
print(type(tuple2))
print(type(tuple3))

1) 빈 tuple을 생성하기 위해서는 '()'를 할당해주면 됩니다. 

2) () 괄호 안에 한 개의 요소가 있는 tuple을 생성할 때는 요소 뒤에 ', '를 붙여줘야 합니다. 

    ','를 붙이지 않았을 때 아래 결과처럼 문자열 자료형을 갖는 걸 확인할 수 있습니다. 

3) 한 개의 요소가 있는 tuple을 생성할 때 요소 뒤에 ', '를 붙여줍니다. 

4) 2개 이상의 요소를 가지는 tuple을 생성할 때는 여러 요소들을 ', '로 구분하여 넣어주기만 하면 됩니다. 

 

2) tuple unpacking

    tuple의 여러 요소들을 여러 변수에 한번에 할당하는 것

friends_tuple = ('Jeff','Alana','Electra')
friends1, friends2, friends3 = friends_tuple

print(friends1)
print(friends2)
print(friends3)

  변수의 순서에 따라 friends tuple의 요소들이 차례대로 할당되는 것을 확인할 수 있습니다. 

3) tuple을 사용하여 swap 하기

friends1 = 'Jeff'
friends2 = 'Alana'

print(friends1)
print(friends2)

friends1, friends2 = friends2, friends1 #swap using tuple

print(friends1)
print(friends2)

c언어에서는 swap을 하기위해 임시 변수를 선언해야 했지만 tuple을 이용하여 한 줄로 swap이 가능합니다. 

swap 하기 전

swap 후

 

4) tuple의 이점

   1. list 보다 tuple이 더 적은 공간이 사용됩니다.

import sys
friends_tuple = 'Jeff' , 'Alana', 'Electra'
friends_list = ['Jeff', 'Alana', 'Electra']

print(sys.getsizeof(friends_tuple))
print(sys.getsizeof(friends_list))

getsizeof()함수를 통해 tuple과 list의 메모리 할당 크기를 확인해보았습니다. 

tuple은 40, list는 48로 tuple에 list에 비해 더 적은 공간이 사용되는 것을 알 수 있었습니다. 

   2. tuple의 요소가 실수로 손상될 수 없다.

def list_func():
    friends_list[0] = 'John'

def tuple_func():
    friends_tuple[0] = 'John'

friends_list = ['Jeff', 'Alana', 'Electra']
friends_tuple = 'Jeff' , 'Alana', 'Electra'

list_func()
print(friends_list)
tuple_func()
print(friends_tuple)

실수로 tuple 요소에 접근하여 수정, 추가, 삭제가 시도되어도 아래 결과처럼 오류가 나는 것을 확인할 수 있습니다. 

 

오늘은 tuple에 대해 정리해보았습니다. 

다음 포스팅으로는 파이썬의 또 다른 특징인 딕셔너리 자료형에 대해 알아보겠습니다.

다음에 만나요!!

Comments