본문 바로가기
목차
Python

[Python] tuple

by ds31x 2023. 10. 6.
728x90
반응형

tuple

 

Tuple은 immutable list라고 자주 불릴 정도로 list와 유사하다.

immutable이기 때문에 한번 assign된 이후 item의 update는 불가(item assignment를 허용하지 않음)함.

  1. update가 안되기 때문에 list 보다 적은 수의 methods를 제공.
  2. 때문에 보다 적은 memory를 차지함.
  3. immutable이다 보니 dictionary의 key로 사용가능함.
  4. 읽기 전용의 sequence가 필요한 경우 많이 사용됨: 참조용으로만 사용되는 데이터에 사용됨.
tuple의 뜻이
순서가 있는 여러 개의 값을 묶은 것임.

 

참고로 list는 comprehension으로 list가 생성되지만,

tuple은 comprehension을 통해 generator를 반환한다.

 

참고: comprehension https://dsaint31.tistory.com/500

 

[Python] List Comprehension

List ComprehensionList comprehension is an expression(표현식) that transforms a collection (not necessarily a list) into a list.list를 생성하는 expression 으로, 원본이 되는 collection 의 모든 item 혹은 일부 item들에 대해 같은 op

dsaint31.tistory.com


생성하기

보통, parenthesis (소가로)를 사용하지만,
assignment에서 =의 오른쪽에서 "comma , 로 어떤 instance들을 결합하여 놓은 경우"

Python은 이를 tuple로 처리한다.

empty_tuple = ()

comma_based_tuple = "first",    # 뒤의 comma때문에 str이 아닌 tuple임.
print(type (comma_based_tuple)) # tuple임을 확인할 수 있음.

recommanded_tuple = ("first",)   # 소가로를 사용하는게 보다 읽기 쉬움
print(type (recommanded_tuple))  # tuple임을 확인할 수 있음.

not_tuple = ("first") # item이 하나인 경우 반드시 comma를 뒤에 붙여줘야 tuple임.
print(type(not_tuple)) # str로 나옴.

Multiple Assignment (다중 할당) 및 Tuple Unpacking

앞서 말한대로 assignment에서

comma로 결합된 instance들은 하나의 tuple로 인식되기 때문에

다음과 같은 할당문이 가능함.

a = 8
b = 10

a, b = b, a # a와 b가 교환됨.
  • assignment의 왼쪽과 오른쪽은 각각 하나의 tuple로 처리됨.
  • 오른쪽은 tuple은 evaluation을 거쳐 (10, 8) 이 되고,
  • 해당 tuple은 tuple unpacking을 통해 ab에 각각 108을 할당한다.
  • 때문에 임시변수 없이도 Python에서는 ab는 값이 교환가능함.

tuple unpacking은 많이 사용되는 방식으로 다음의 예제를 참고하라.

a,b,c = (100, 200, 300)

a,b,c = 8, 9, 10 # comma로 8,9,10이 결합된 형태이므로 등호의 오른쪽이 tuple임.

다른 collection에서 생성하기.

다른 collection으로부터 tuple을 생성하는 것도 가능함.

l = [1,2,3]
t = tuple(l)

 

Collection 객체는 여러 값을 그룹으로 저장할 수 있는 Python의 자료형을 가리키며, collections.abc.Collection 을 상속하고 있음.

2024.04.15 - [Python] - [Python] collections.abc

 

[Python] collections.abc

2023.10.06 - [Pages] - [Python] Collectionscollections.abc 와 Python의 DataStructure.Python의 Data structure는 실제적으로 collections.abc 라는 abstract base class (abc) mechanism를 통한 hierarchy로 구성된다: type은 module임.일반적

ds31x.tistory.com


item에 접근하기.

tuple은 itme별 순서가 의미를 가지는 sequence type이므로
sqaure bracket과 index로 개별 item에 접근이 가능하다: immutable이므로 읽기 접근만 가능.

t = ("first", "second", "third")
print(t[0]) # "first"
  • Python은 zero based index를 사용함.

관련 Operations

list와 거의 유사하다.

  • tuple은 immutable이므로
  • 갱신되는 게 아닌 새로운 객체가 만들어지고
  • variable이 해당 새로운 객체를 가리키는 동작이 이루어진다.

2023.07.12 - [Python] - [Python] list (sequence type) : summary

 

[Python] list (sequence type) : summary

list (Sequence Type) : Summary list는 ordered mutable collection으로, collection을 위한 python data type들 중 가장 많이 사용된다. C에서의 array와 같이 가장 기본적인 collection임. 단, heterogeneous item을 가질 수 있으며,

ds31x.tistory.com


Relational operations (or Comparison operations)

알파벳 및 숫자의 크기를 이용한 대소 비교가 이루어짐.

  • item별로 비교가 이루어짐.
  • itme 비교에서 한쪽의 item이 없는 경우 보다 작은 값으로 판정.
a = (35, 10, "abc")
b = (35, 10,)

print(f'{(a == b)=}') # False
print(f'{(a <= b)=}') # False
print(f'{(a >= b)=}') # True
print(f'{(a < b)=}')  # False
print(f'{(a > b)=}')  # True

 

참고로, Unicode상 영어의 대문자가 소문자보다 앞에 놓이며, 때문에 대문자와 소문자를 대소 비교시 대문자가 작은 것으로 나옴.


복제 * 및 concatenate +

* 는 해당 item들이 반복 추가된 새로운 tuple 객체를 생성.

t = ('first', 'second')
print(id(t), type(t))
t = t*4
print(id(t), type(t))

 

+ 는 operand를 합친 새로운 tuple 객체를 생성.

t0 = ('first', 'second')
t1 = (3, 4)
t = t0 + t1
print(t)

augmented operations *=, += 의 경우 (=in-place operations)

기존의 tuple의 업데이트가 아닌

실제로는 해당 결과에 해당하는 새로운 tuple 객체 생성이 되는 것임을 유의할 것.


관련 ipynb 파일.

https://gist.github.com/dsaint31x/c4853756e5b0bd9d720fe39cbb4d9e8c

 

py_tuple.ipynb

py_tuple.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

728x90