1. 튜플 ( Tuple )

튜플은 list와 비슷하지만, 소괄호( )로 표기하며, immutable( 변경 불가 )한 자료형입니다.


1) list, set으로 변경 가능

t = (3, 2, 1)
s = set(t) # set으로 변환
print(s) # set([1, 2, 3])

l = list(t) # list로 변환
print(l) # [3, 2, 1]



2) immutable ( 변경 불가능 )

튜플은 immutable 합니다.

t = (3, 2, 1)
t[1] = 10 # TypeError: 'tuple' object does not support item assignment



3) packing과 unpacking

packing이란 나열된 객체를 tuple로 저장하는 것을 말하고,

unpacking이란 tuple안의 원소를 각각의 변수로 할당하는 것을 말합니다.

# packing : 나열된 객체를 tuple로 저장하는 것을 말한다.
t = 10, 20, 30, 'python'
print(t, type(t)) # (10, 20, 30, 'python') <class 'tuple'>


# unpacking : tuple안의 원소를 각각의 변수로 할당하는 것을 말한다.
a, b, c, d = t
print(a, b, c, d) # 10 20 30 python

# extended unpacking
a, *b = t # *b list unpacking이 된다.
print(a, b) # 10 [20, 30, 'python']

*a, b = t
print(a, b) # [10, 20, 30] python

a, *b, c = t
print(a, b, c) # 10 [20, 30] python





2. 딕셔너리 ( Dictionary )

딕셔너리는 다른 언어의 해시 테이블( hash table ) 또는 맵( map )과 같습니다.

딕셔너리의 각 원소는 key와 value를 하나의 쌍으로 하여 형성됩니다.


1) 딕셔너리를 생성하는 여러가지 방법

# 1) { }
fruit = {'apple': 100, 'banana': 50}
print(type(fruit)) # <class 'dict'>

# 2) dict() 함수의 인자로 key=value를 전달
d = dict(apple=100, banana=50)
print(d, type(d)) # {'apple': 100, 'banana': 50} <class 'dict'>

# 3) dict() 함수의 인자로 튜플을 원소로 갖는 리스트를 전달
d2 = dict([('apple', 100), ('banana', 50)])
print(d2, type(d2)) # {'apple': 100, 'banana': 50} <class 'dict'>

# 4) zip
keys = {'apple', 'banana'}
values = {100, 50}
d3 = dict(zip(keys, values))
print(d3, type(d3)) # {'banana': 50, 'apple': 100} <class 'dict'>

# 5) 딕셔너리의 key로 사용할 수 있는 자료형은 거의 제한이 없다.
d4 = dict()
d4[10] = '정수 가능'
d4[True] = 'bool 가능'
d4[(1,2,3)] = '튜플 가능'
# d4[[1,2,3]] = '리스트는 불가능' # TypeError: unhashable type: 'list
# # => key는 변경 불가능해야 하지만, list mutable하다.
print(d4) # {10: '정수 가능', True: 'bool 가능', (1, 2, 3): '튜플 가능'}



2) 요소 추가 및 value 조회

fruit = {'apple': 100, 'banana': 50}
fruit['peach'] = 60
fruit['tomato'] = 80
print(fruit) # {'tomato': 80, 'apple': 100, 'peach': 60, 'banana': 50}
print(fruit['apple']) # 100


딕셔너리는 + 연산을 지원하지 않습니다.

즉 + 연산으로 요소를 추가할 수 없습니다.

print(fruit + {"melon": 70})       # TypeError: unsupported operand type(s) for +: 'dict' and 'dict'



3) mutable ( 변경 가능 )

딕셔너리는 mutable 합니다.

fruit = {'apple': 100, 'banana': 50}
fruit['apple'] = 80
print(fruit) # {'apple': 80, 'banana': 50}



4) 함수 및 메서드

fruit = {'apple': 100, 'banana': 50}

# keys()
keys = fruit.keys()
print(keys, type(keys)) # dict_keys(['apple', 'banana']) <class 'dict_keys'>

# values()
values = fruit.values()
print(values, type(values)) # dict_values([80, 50]) <class 'dict_values'>


# items()
items = fruit.items() # key, value 쌍을 튜플로 만들고, 튜플을 원소로 갖는 리스트가 반환된다.
print(items, type(items)) # dict_items([('apple', 80), ('banana', 50)]) <class 'dict_items'>


# get()
price = fruit.get('apple')
print(price) # 80

print(fruit.get('melon')) # None => 없는 key get() 할 경우 예외가 발생하지 않는다.
# print(fruit["melon"]) # KeyError: 'melon' => 예외 발생

print(fruit.get('melon', 100)) # 100 => 없는 key일 경우 default를 할당할 수 있다.


fruit['peach'] = 60
fruit['tomato'] = 80
# pop()
value = fruit.pop('banana') # value를 가져오면서 삭제
print(value) # 50
print(fruit) # {'apple': 80, 'peach': 60, 'tomato': 80}

# popitem()
item = fruit.popitem() # 마지막 원소를 튜플로 가져오기
print(item) # ('tomato', 80)
print(fruit) # {'apple': 80, 'peach': 60}



5) 반복문으로 딕셔너리 원소 조회

fruit = {'apple': 100, 'banana': 50}

for key, value in fruit.items(): # unpacking
print(key + " : " + str(value) )
# apple : 100
# banana : 50





3. 순차 자료형을 위한 함수

순차 자료형이란 bytes, str, list, tuple과 같이 원소가 순서를 갖는 자료형을 말합니다.

python에서는 순차 자료형을 위한 함수들을 제공합니다.


1) range()

range() 함수는 순차적인 정수 리스트를 만들 때 사용합니다.

seq = range(10)
print(seq, type(seq)) # range(0, 10) <class 'range'>

li = list(range(5, 10))
print(li, type(li)) # [5, 6, 7, 8, 9] <class 'list'>



2) enumerate()

enumerate() 함수는 순차 자료형에서 현재 아이템의 index를 함께 처리하고자 할 때 사용합니다.

예제에서 index와 value값을 할당하기 위해 튜플의 unpacking 개념이 활용됩니다.

li = ['apple', 'banana', 'melon']
for idx, value in enumerate(li):
print(str(idx) + " - "+ value)
# 0 - apple
# 1 - banana
# 2 - melon



3) zip()

zip() 함수는 여러 개의 순차 자료형을 튜플로 만들어서, 이 튜플을 원소로 하는 리스트를 생성할 때 사용합니다.

seq1 = {'foo', 'goo', 'hoo'}
seq2 = {'one', 'two', 'three'}

z = zip(seq1, seq2)
for t in z:
print(t, type(t))
#('hoo', 'three') <class 'tuple'>
# ('foo', 'one') <class 'tuple'>
# ('goo', 'two') <class 'tuple'>



이상으로 자료형 Tuple, Dictionary과 순차 자료형을 위한 몇 가지의 함수들을 알아보았습니다