5.3. Tuples and Sequences
튜플과 시퀀스들
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.
리스트와 문자열은 둘 모두 인덱싱(순서매기기)와 구간지정 기능을 가지고 있습니다. 리스트와 문자열은 시퀀스 데이터 유형의 예 입니다. (Sequence Types - list, tuple, range를 참고하십시오. 아직 연결되지 않음) 파이썬은 계속해서 발달해가는 언어이기 때문에, 새로운 시퀀스 데이터 유형이 추가될 수도 있습니다. tuple역시 시퀀스 데이터 유형 입니다.
A tuple consists of a number of values separated by commas, for instance:
하나의 튜플은 콤마( , )로 구분된 여러개의 값들로 구성됩니다.
>>> t = 12345, 54321, 'hello!' : 튜플에 값을 설정한다.
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # 튜플은 중첩해서 사용할 수 있다:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # 튜플은 내용물을 변경할 수 없다:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.
튜플을 출력하면 그 결과는 언제나 괄호안에 담겨 있습니다. 이로 인해 중첩된 튜플이 정확하게 실행될 수 있. 튜플을 만들 때는 괄호를 써도 되고 안 써도 됩니다. 비록 괄호를 사용하는 일이 더 잦지만 말입니다. (만약 튜플이 더 큰 상위 표현식의 부분이라면, 괄호를 사용해야 합니다.)
개별적인 항목은 튜플에 추가할 수 없습니다. 하지만 리스트와 비슷하게 가변객체를 포함할 수는 있습니다.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
튜플이 리스트와 비슷해 보이지만, 둘은 종종 서로 다른 상황에 다른 목적을 가지고 사용됩니다. 튜플은 변형이 불가능 합니다. 그리고 종종 해체나 인덱싱를 통해서만 접근할 수 있는 다종 시퀀스 요소를 포함합니다. (해체에 관해서는 뒤에서 다시 다루겠습니다.) (이름이 지어진 튜플의 경우는 속성에 따라 추정해야 합니다.) 리스트는 변경이 가능하며, 대개 동일한 요소들로 구성됩니다. 또한 반복적으로 접근할 수 있습니다.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
0과 1이 항목에 포함된 튜플은 특별하게 다뤄야 합니다. 튜플은 이 외에도 몇가지 문제점을 안고 있습니다. 빈 튜플은 한 쌍의 빈 괄호로 만들어집니다. 하나의 항목만 포함된 경우, 그 항목의 뒤에 콤마를 붙여주어야 합니다. 하나의 값을 괄호로 둘러싸기만 해서는 튜플을 만들기에 부적절합니다. 괄호가 있는 경우에도 항목의 뒤에 콤마를 붙여줍니다. 시각적으로 보기는 싫지만 다음 예시와 같습니다.
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
The statement t = 12345, 54321, 'hello!'
is an example of tuple packing: the values 12345
, 54321
and 'hello!'
are packed together in a tuple. The reverse operation is also possible:
다음 예시 t = 12345, 54321, 'hello!'
는 숫자와 문자열이 하나의 튜플에 함께 담길 수 있다는 것을 보여줍니다. 반대의 경우도 가능합니다.
x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
위 예시는 등호 오른쪽의 시퀀스 해체와 작동을 위해 사용됩니다. 해체되지 않은 시퀀스는 등호 왼쪽에 다양한 종류의 변수를 가지고 있습니다. 다중 할당은 그저 튜플 조립과 시퀀스 해체의 조합이라는 점을 주목하십시오.