본문 바로가기

Program Languages/Python

파이썬 자료형(Data type)

이번 포스트에서는 파이썬의 자료형에 대해서 알아보려고 합니다.

 

우선 자료(Data)라는 사전적의미를 인터넷에서 찾아보자면

 

자료(資料, data, 데이터, 문화어: 데타)는 문자, 숫자, 소리, 그림, 영상, 단어 등의 형태로 된 의미 단위이다.

출처: https://ko.wikipedia.org/wiki/%EC%9E%90%EB%A3%8C_by_TedBot

 

자료형(資料型) 또는 데이터 타입(영어: data type)은 컴퓨터 과학과 프로그래밍 언어에서 실수치, 정수, 불린 자료형 따위의 여러 종류의 데이터를 식별하는 분류

출처: https://ko.wikipedia.org/wiki/%EC%9E%90%EB%A3%8C%ED%98%95_by_LR0725

 

 

즉, 컴퓨터에서 자료형이라는 것은  어떤 자료에 대해 컴퓨터가  해석할 수 있는 언어로 변환된(현재의 컴퓨터 시스템에서는 일련의 0과 1들로 표현될 수 있는) 여러 형태의 데이터의 분류라고 생각해 볼 수 있습니다.

 

 

본론으로 돌아와 파이썬의 기본 자료형을 표로 정리하자면,

대분류 중분류 python 함수명 기본 메모리 점유 용량 추가되는 점유 용량
숫자(Number) 정수(integer) int 28bytes 절댓값으로 할당 값
마다(per)
4byte씩 추가
실수(real number) float 24bytes 0
복소수(complex number) complex 32bytes 0
불리언(Boolean)   bool 28bytes 0
집합(Set)   set 224bytes y=x^2 꼴 그이상으로 기하급수적으로 증가
사전테이블(Dictionary)   dict 240bytes
연속데이터
(Sequence)
문자열(String) str 49bytes +(1~4)byte/character
리스트(List) list 64bytes +8byte/item
튜플(Tuple) tuple 48bytes
범위(Range) range 48bytes 0
바이트배열(Bytes) bytes 33bytes +1byte/item
bytearray 56bytes +1byte/item 이지만 해석기에서 실제 할당된 부분외에 일부분 메모리 까지 미리 점유함

파이썬 자료형이 점유하는 메모리 용량에 대해서는 이미 다른 유저가 확인해 주셨기 때문에 https://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python 을 참고하였습니다.

 

더보기

T.M.I.


위의 표를 참고해 보면 평균적인 기본 메모리 점유 용량이 크다는 것을 알 수 있는데 이것은 파이썬 스크립트 해석기 프로그램이 어셈블리 문법 기반이 아닌 사람이 이해하기 쉬운 고수준(high-level) 언어를 기반으로 설계되었기 때문인데요, 정확히는 각각의 데이터 타입들이 사실은 클래스 구현을 통해 연산이 구현되어 있기 때문에 초기에 할당되는 메모리 용량이 높은 것 입니다.

따라서 일반적인 c언어로 프로그래밍을 하는 것보다 파이썬을 사용해 프로그래밍하는 것에서 메모리와 비용 관리에 주의를 기울여야 합니다.

 

 

 

다음은 위의 데이터 타입들을 어떻게 사용하냐에 대해 살펴보겠습니다.

#정수의 경우
integer = 1
integer = int(-1)
integer = int("123")
integer = int("a0",16)#16진수 숫자 문자열로 부터 파싱

#실수(real number)의 경우
real_number = 1.0
real_number = float(-1.01)
real_number = float("1.234")

#복소수(complex)의 경우
complex_number = 1+2j #(실수부분+허수부분)
complex_number = complex(-1,2)#(실수부분,허수부분)

#부울(boolean-참/거짓 상태 표현)의 경우
boolean = True
boolean = False
boolean = bool(False)
boolean = bool(0)
boolean = bool(1)
boolean = bool("true")
boolean = bool("True")

#범위의 경우(range 객체는 읽기전용)
start=10
end = 20
increment=2

#값들은 start,start+increment,start+2*increment,...,((end-1)이하인 값중 (start+k*increment)이 만족하는 마지막 값)
rng = range(start,end,increment)

#값 범위는 0~(end-1)
rng = range(end)

#값 범위는 start~(end-1)
rng = range(start,end)

#리스트의 경우
_list = [1,2,3]
_list = [1,2]+[3,4]
repeat_count = 2
_list = [0]*repeat_count
_list = [0 for _ in range(repeat_count)]
_list = list([3,4,3])
if(True is True):
    _list = list()
    _list.append(3)
    _list.append(2)

#문자열(String)의 경우
string = "string"
string = str("string")
string = str(chr(97))
if(True is True):
    string = list("string")
    string = "".join(string)
if(True is True):
    string = ['h','i']
    string = "".join(string)

#튜플의 경우
tup = (1,2,3.0)
tup = (1,2)+(3,4)
tup = tuple()
tup = tuple([1,2,3])

#집합(set)의 경우
Aset = {1,2,1}
Aset = {a for a in ranage(10)}
Aset = set([1,3,1])
if(True is True):
    Aset = set()
    Aset.add(1)
    Aset.add(3)
    Aset.add(4)
    Aset.add(1)
    Aset.remove(4)
    
#사전테이블의 경우
Aset = {"key1":"value1","key2":123}
Aset = {a:a*2 for a in range(10)}
if(True is True):
    Aset = dict()
    Aset["key1"] = "value1"
    Aset.update([("key2",123),("key3",321),("key4","v")])
    del Aset["key3"]
    Aset.pop("key4")
    
#바이트 배열의 경우
byte = b'123'
Bytes= b'\x01\x04'
Bytes = bytes([1,2,3])#읽기전용(설정된 이후 값 수정 안됨)
Bytes = bytearray([1,2,3])#배열 원소 읽기/쓰기 가능
Bytes = "string bytes".encode("utf-8")