리스트와 비슷하지만 아이템 변경이 불가능하다
- 리스트 : 아이템 변경(수정, 삭제) 가능
- 아이템 변경 불가능
students = ('짱구', '철수', '유리', '훈이', '맹구')
print(f'students = {students}')
print(f'students = {type(students)}')
💡result
students = ('짱구', '철수', '유리', '훈이', '맹구')
students = <class 'tuple'>
인덱스 : 튜플도 리스트와 마찬가지로 아이템에 자동으로 부여되는 번호표가 있다.
students = ('짱구', '철수', '유리', '훈이', '맹구')
for i in range(len(students)):
print(f'student[{i}] = {students[i]}')
💡result
student[0] = 짱구
student[1] = 철수
student[2] = 유리
student[3] = 훈이
student[4] = 맹구
students = ('짱구', '철수', '유리', '훈이', '맹구')
for i in range(len(students)):
if i % 2 == 0:
print(f'짝 : student[{i}] = {students[i]}')
else:
print(f'홀 : student[{i}] = {students[i]}')
💡result
짝 : student[0] = 짱구
홀 : student[1] = 철수
짝 : student[2] = 유리
홀 : student[3] = 훈이
짝 : student[4] = 맹구
students = ('짱구', '철수', '유리', '훈이', '맹구')
inputName = input('학생 이름 : ')
if inputName not in students:
print(f'{inputName}은 존재하지 않는 학생입니다.')
else:
print(f'{inputName}은 존재하는 학생입니다.')
💡result
학생 이름 : 서태웅
서태웅은 존재하지 않는 학생입니다
# 비속어 판단 프로그램
wrongWord = ('존나', '미친', '쪼갬', '닥쳐', '빡침')
sentence = '오늘 날씨 존나 좋아. ' \
'근데 버스 눈 앞에서 놓쳐서 개빡침.' \
' 그래서 친구가 옆에서 개쪼갬'
for wrong in wrongWord:
if wrong in sentence:
print(f'비속어 : [{wrong}] 사용❗')
💡result
비속어 : [존나] 사용❗
비속어 : [쪼갬] 사용❗
비속어 : [빡침] 사용❗
# 튜플 길이
students = ('짱구', '철수', '유리', '훈이', '맹구')
print(f'students 길이 : {len(students)}')
n = 0
while n < len(students):
print(f'student[{n}] : {students[n]}')
n += 1
💡result
students 길이 : 5
student[0] : 짱구
student[1] : 철수
student[2] : 유리
student[3] : 훈이
student[4] : 맹구
두 개의 튜플을 결합할 수 있다 .
# 튜플 결합
students1 = ('짱구', '철수', '유리')
students2 = ('훈이', '맹구')
print(students1)
print(students2)
print(students1 + students2)
💡result
('짱구', '철수', '유리')
('훈이', '맹구')
('짱구', '철수', '유리', '훈이', '맹구')
리스트에서 사용할 수 있는 extend() 함수는 사용할 수 없다.
# extend()
print(students1.extend(students2))
💡result
AttributeError: 'tuple' object has no attribute 'extend'
myFavorite = (3, 8, 12, 4, 1, 6)
friendFavorite = (1, 2, 3, 4, 5, 6)
for friend in friendFavorite:
if friend not in myFavorite:
myFavorite = myFavorite + (friend,) #int타입을 tuple로 변경
print(f'myFavorite : {myFavorite}')
💡result
myFavorite : (3, 8, 12, 4, 1, 6, 2, 5)
리스트와 마찬가지로 [n:m]을 이용하면 리스트에서 원하는 아이템을 뽑아낼 수 있다.
students = ('짱구', '철수', '유리', '훈이', '맹구')
print(f'students[2:] : {students[2:]}')
print(f'students[1:4] : {students[1:5]}')
print(f'students[:10] : {students[:10]}')
print(f'students[-1:2] : {students[-1:2]}')
print(f'students[-4:2] : {students[-4:2]}')
print(f'students[-4:1] : {students[-4:1]}')
print(f'students[-4:5] : {students[-4:5]}')
print(f'students[-4:] : {students[-4:]}')
print(f'students[1:-2] : {students[1:-2]}')
💡result
students[1:4] : ('철수', '유리', '훈이', '맹구')
students[:10] : ('짱구', '철수', '유리', '훈이', '맹구')
students[-1:2] : ()
students[-4:2] : ('철수',)
students[-4:1] : ()
students[-4:5] : ('철수', '유리', '훈이', '맹구')
students[-4:] : ('철수', '유리', '훈이', '맹구')
students[1:-2] : ('철수', '유리')
print(f'students[2::2] : {students[2::2]}')
students[2::2] : ('유리', '맹구')