python/python 기초
6. Python 데이터 타입 3 - tuple(튜플)
Memory!
2022. 4. 7. 23:44
728x90
반응형
Python의 데이터 타입 종류는 아래와 같습니다.
- Numeric Types: int(정수), float(소수), complex(복소수)
- Sequence Types: str(문자열), list(리스트), tuple(튜플)
- Mapping Type: dict(딕셔너리)
- Set Types: set(집합)
- Boolean Type: bool(불리언)
Binary Types: bytes, bytearray, memoryview
이번에는 tuple(튜플)에 대해 알아보겠습다.
tuple은 List와 거의 동일합니다.
1. List와 Tuple의 다른점
- 리스트는 []로 쌓여있고 []로 만들지만 tuple은 ()를 사용한다.
- 리스트는 내부 값을 수정, 삭제, 삽입이 가능하나 tuple은 불가능하다.
2. tuple 생성하기
- list와 다르게 ()로 생성합니다.
>>> intTuple = (1,2,3,4,5)
>>> strTuple = ("itgilajavy", "tistory", "com")
>>> print(intTuple)
(1, 2, 3, 4, 5)
>>> print(strTuple)
('itgilajavy', 'tistory', 'com')
3. tuple 덧셈(이어붙이기), 반복
- list와 동일하게 +, *로 tuple간의 이어붙이기와 반복이 가능합니다.
>>> print(intTuple + strTuple)
(1, 2, 3, 4, 5, 'itgilajavy', 'tistory', 'com')
>>> print(intTuple * 3)
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
4. index 로 접근하기
>>> print(intTuple[1])
2
>>> print(strTuple[0])
itgilajavy
tuple의 값을 변경하려면 에러가 납니다.
>>> intTuple[1] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
역시 삭제를 하려고 해도 에러가 납니다.
>>> del(intTuple[1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
5. tuple() 명령어로 생성 가능
- list와 같이 tuple()로 list 데이터를 tuple로 변경하여 생성 가능합니다.
>>> a = tuple("abcdefg")
>>> print(a)
('a', 'b', 'c', 'd', 'e', 'f', 'g')
# list를 tuple로
>>> b = [1,2,3,4,5]
>>> c = tuple(b)
>>> print(c)
(1, 2, 3, 4, 5)
# tuple을 list로
>>> d = list(intTuple)
>>> print(d)
[1, 2, 3, 4, 5]
728x90
반응형