라일락 꽃이 피는 날

[Python] tuple (튜플) 본문

프로그래밍/Python

[Python] tuple (튜플)

eunki 2021. 5. 30. 20:56
728x90

sequence type : 순서가 정해져 있는 자료형
- mutation : 변경 가능 자료형  ex) list
- immutation : 변경 불가능 자료형  ex) tuple

 

 

 


tuple (튜플)

 

변수명 = (value1, value2, ...)
변수명 = tuple([value1, value2, ...])

tup = (1, 2, 3)

print(tup)  # (1, 2, 3)

print(tup[0])  # 1
print(tup[1])  # 2
print(tup[-1])  # 3
print(tup[-3])  # 1

print(tup[0:2])  # (1, 2)
print(tup[1:3])  # (2, 3)
print(tup[-3:-1])  # (1, 2)
print(tup[-2:])  # (2, 3)
tup = (('a', 'b'), ('c', 'd'), ('e', 'f'))

print(tup[0])  # ('a', 'b')
print(tup[1][1])  # d
print(tup[2][0])  # e
tup = (('a', 'b'), ('c', 'd'), ('e', 'f'))

for val in tup:
    print(val[0], val[1])

# a b
# c d
# e f
tup = (('a', 'b'), ('c', 'd'), ('e', 'f'))

for val1, val2 in tup:
    print(val1, val2)
    
# a b
# c d
# e f

 

 

tuple 함수

 

count(value) 튜플에서 일치하는 값의 개수를 반환
index(value) 튜플에서 일치하는 값의 인덱스 번호를 반환
tup = (1, 2, 3, 1, 2)

tup.count(2)  # 2

# 2를 index 0부터 찾는다
tup.index(2)  # 1

# 2를 index 4부터 찾는다
tup.index(2, 4)  # 4
728x90

'프로그래밍 > Python' 카테고리의 다른 글

[Python] dictionary (사전)  (0) 2021.06.01
[Python] list (리스트)  (0) 2021.05.30
[Python] 반복문  (0) 2021.05.21
[Python] 조건문  (0) 2021.05.21
[Python] random  (0) 2021.05.21