튜플(Tuple)
튜플은 소괄호 (()
)를 사용하며 리스트와 유사한 기능을 가진다. 하지만 튜플은 불변(immutable) 자료형으로, 한 번 생성된 후에는 요소를 변경할 수 없다. 따라서 리스트에서 제공되는 메서드(append
, remove
, pop
등)는 사용할 수 없다.
python
a = (5, 3, 1, 4, 2)
b = tuple((5, 3, 1, 4, 2))
c = ("python", 500, 3.14)
d = ([1, 3, 2], (10, 20, 30), "java", "C++")
print(type(a), type(b), type(c), type(d))
plaintext
<class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'tuple'>
튜플 선언시 다음과 같은 방법을 통해 선언할 경우 튜플이 되지 않는다.
python
a = ([5])
b = (5)
c = ("python")
print(type(a), type(b), type(c))
plaintext
<class 'list'> <class 'int'> <class 'str'>
리스트는 원소를 하나만 갖도록 선언하는 것이 가능하지만, 튜플은 원소를 하나만 갖도록 선언할 때 반드시 쉼표(,
)를 사용해야 한다.
python
a = ([5],)
b = (5,)
c = ("python",)
print(type(a), type(b), type(c))
plaintext
<class 'tuple'> <class 'tuple'> <class 'tuple'>
리스트와 튜플은 다음과 같은 방법으로 서로 변환할 수 있다.
python
data1 = [1, 2, 3, 4, 5]
data2 = (1, 2, 3, 4, 5)
v1 = tuple(data1)
v2 = list(data2)
print(v1, v2)
plaintext
(1, 2, 3, 4, 5) [1, 2, 3, 4, 5]
튜플이 다음과 같이 정의되어 있다면 각 명령을 실행했을 때 발생하는 에러는 다음과 같다.a = (5, 3, 1, 4, 2)
명령 | 실행 결과 |
---|---|
a[0] = 4 | TypeError: 'tuple' object does not support item assignment |
a.remove(1) | AttributeError: 'tuple' object has no attribute 'remove' |
a.pop() | AttributeError: 'tuple' object has no attribute 'pop' |
del a[1] | TypeError: 'tuple' object doesn't support item deletion |
a.append(6) | AttributeError: 'tuple' object has no attribute 'append' |
a.extend((10, 30)) | AttributeError: 'tuple' object has no attribute 'extend' |
a.sort() | AttributeError: 'tuple' object has no attribute 'sort' |
튜플에서 사용할 수 있는 메서드는 count
와 index
가 있으며, 리스트에서 사용했던 내장함수를 모두 동일하게 사용할 수 있다.
python
a = ("python", "C++", "JAVA", "GO")
b = (4, 2, 5, 1, 3)
명령 | 실행 결과 |
---|---|
a[1:2] | ('C++',) |
a[1:3] | ('C++', 'JAVA') |
b[-3:-1] | (5, 1) |
a.index("JAVA") | 2 |
a.count("C++") | 1 |
len(a) | 4 |
sorted(b) | [1, 2, 3, 4, 5] |