Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 튜플 데이터 유형

<시간/>

튜플은 목록과 유사한 또 다른 시퀀스 데이터 유형입니다. 튜플은 쉼표로 구분된 여러 값으로 구성됩니다. 그러나 목록과 달리 튜플은 괄호로 묶입니다.

예시

목록과 튜플의 주요 차이점은 다음과 같습니다. 목록은 대괄호( [ ] )로 묶여 있고 요소와 크기를 변경할 수 있는 반면 튜플은 괄호( ( ))로 묶여 업데이트할 수 없습니다. 튜플은 읽기 전용으로 생각할 수 있습니다. 기울기. 예를 들어 -

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

출력

이것은 다음 결과를 생성합니다 -

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

다음 코드는 허용되지 않는 튜플 업데이트를 시도했기 때문에 튜플에 유효하지 않습니다. 목록에서도 비슷한 경우가 가능합니다. −

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list