List | Tuple | |
---|---|---|
Type | mutable. unhashable, 중첩가능 | immutable. hashable, 중첩불가 |
Iteration | 가능하지만 시간이 더 소요된다 | 가능하고 더 빠르다 |
Appropriate for | 삽입 및 삭제 작업에 유용하다 | 요소 접근과 같은 읽기전용 작업에 유용하다 |
Memory | 더 많은 메모리 소모 | 메모리 덜 소모 |
Methods | 많은 내장 메서드 제공 | 더 적은 내장 메서드 |
Error prone | 에러 발생하기 쉽다 | 더 안전하다 |
__hash__()
a= (1,2,3,4,5,6,7,8,9,0)
b= [1,2,3,4,5,6,7,8,9,0]
print('a=',a.__hash__()) # a는 hash값이 나오지만
print('b=',b.__hash__()) # b는 TypeError: 'NoneType' object is not callable
key_val= {('alpha','bravo'):123} #Valid 튜플은 key로 사용가능
key_val = {['alpha','bravo']:123} #Invalid 리스트는 key로 사용불가
__sizeof__()
a= (1,2,3,4,5,6,7,8,9,0)
b= [1,2,3,4,5,6,7,8,9,0]
print('a=',a.__sizeof__()) # a= 104
print('b=',b.__sizeof__()) # b= 120
dir()
print(dir([])) # 리스트를 확인해보면
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
print(dir(())) # 튜플을 확인해보면
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'count',
'index']
→ Sequence Data Type 이다.
→ 중복 요소를 허용한다.
→ 순서가 있다.
→ 연결, 반복, 인덱싱 및 슬라이싱이 가능하다.
→ len, count, index 등 일반적인 메서드가 있다.
→ 동일한 데이터 타입뿐만 아니라 서로 타입이 달라도 넣을 수 있다.
Set | Dictionary |
---|---|
in single row | key value pairs |
elements are not duplicated | Keys are not duplicated |
중복제거에 유용하다 | 효율적인 요소찾기에 유용하다 |
dict.keys()
: 키 리스트 가져오기
dict.values()
: 값 리스트 가져오기
dict.items()
: 키, 값 쌍 모두 가져오기
dict.get(key)
: 키를 사용하여 값 얻기
dict.get(key, default_value)
: 딕셔너리 안에 찾으려는 Key 값이 없을 경우 디폴트 값을 대신 가져옴
- dict[key]와 dict.get(key)의 차이
존재하지 않는 키인 경우dict[key]
는 Key 오류를 발생시킨다.
반면,dict.get(key)
는 None을 돌려준다.
dict.clear()
: 모든 키와 값 지우기
dict.pop(key)
: 특정 키-값 쌍을 삭제하고 삭제한 값을 반환
dict.pop(key, default_value)
: 기본값을 지정하면 해당 키가 없을 때 기본값만 반환
dict.popitem()
: 마지막 키-값 쌍을 삭제(파이썬 3.6 이상), 임의의 키-값 쌍을 삭제(파이썬 3.5 이하)
# key만 입력하면 모든 값은 None으로 저장된다.
keys = ['a', 'b', 'c', 'd'] # 튜플도 가능
x = dict.fromkeys(keys)
x # {'a': None, 'b': None, 'c': None, 'd': None}
# 값까지 입력하면 모든 값으로 저장된다.
y = dict.fromkeys(keys, 100)
y # {'a': 100, 'b': 100, 'c': 100, 'd': 100}
세트는 순서가 없다.
-> 인덱싱으로 값을 얻을 수 없다.
-> 리스트나 튜플로 변환 후 인덱싱 가능하다.
세트 안에 요소로 세트를 넣을 수 없다.
합집합 set1 | set2
, set.union(set1,set2)
교집합 set1 & set2
, set.intersection(set1, set2)
차집합 set1 - set2
, set.difference(set1, set2)
대칭차집합 set ^ set2
, set.symmetric_difference(set1, set2)
set.add(el)
: 요소 추가하기
set.remove(el)
: 특정 요소를 삭제하고 요소가 없으면 에러를 발생
set.discard(el)
: 특정 요소를 삭제하고 요소가 없으면 그냥 넘어가기
set.pop()
: 임의의 요소를 삭제하고 반환
set.clear()
: 집합의 모든 요소 삭제
- 참조목록
https://www.tutorialspoint.com/difference-between-list-and-tuples-in-python
https://www.programiz.com/python-programming/list-vs-tuples
https://pythonsimplified.com/python-list-vs-tuple/
https://www.geeksforgeeks.org/differences-and-applications-of-list-tuple-set-and-dictionary-in-python/
https://dzone.com/articles/python-memo-2-dictionary-vs-set-1