[Python] (Data) Type: Summary

2023. 6. 12. 17:22·Programming
728x90
728x90

1. Type 이란?

Programming에서 사용되는 모든 value 혹은 object 들의 종류 (category) 를 (data) type이라고 부름.

수학에서 숫자의 종류(type)를 실수, 정수, 자연수 등으로 나누는 것을 생각하면 쉽다.

Programming에서는

  • 문자 (str)들도 다루며, 여러 object를 묶어 하나로 처리 (collection) 하기도 하기 때문에
  • 보다 다양한 type을 지원한다.

 

프로그래밍 언어들을 이들 type에 대한 체크나 지원 방식에 따라 다음으로 분류됨.

https://ds31x.tistory.com/563

 

Typing: dynamic vs. static and strong vs. weak

타입 검사는 프로그램의 type safety를 보장하기 위한 장치이며, 언제(컴파일/실행 시점) 검사하느냐와 얼마나 엄격하게 검사하느냐에 따라 프로그래밍 언어가 분류됨:Static vs Dynamic: 언제 타입을

ds31x.tistory.com


2. Programming에서 Type 이란?

Programming에서 특정 object가 어떤 type인지가 결정되면 다음의 내용이 해당 type에 따라 결정된다.

  • 해당 object가 가질 수 있는 value들의 집합 이 결정됨. (예를 들어 int type이면 정수만을 값으로 가질 수 있음)
  • 해당 object를 operand(피연산자)로 가질 수 있는 operator(연산자)들이 결정됨.
    (문자와 같은 type은 나눗셈 operator의 operand가 될 수 없음)

3. Python에서 Type 확인하기

Python의 모든 obj에 대해 해당 type을 확인하려면
다음과 같이 type 함수에 해당 object를 argument로 넣어주면 됨.

type(obj)

4. Python에서 Type의 분류

Python에서 많이 사용되는 표준데이터 type들은 다음과 같음 (기본적인 type들을 의미함).

  • Numeric Type
    • int : 정수 (integer)
    • float : 실수 (real number, floating point)
    • complex : 복소수 (complex)
  • Boolean Type
    • bool : True와 False 만을 값으로 가짐. (boolean)
  • Sequence Type
    • str : 글자 하나씩의 관점에서는 sequence이지만, 문자열을 위해 사용됨 (collection의 성질보다 텍스트를 위한 type 성격이 강함). text string 또는 string이라고 불림.
    • list : item의 index로 순서를 사용하는 sequence type의 대표. mutable임.
    • tuple : immutaple list라고 불림.
  • Set Type
    • set : 수학에서의 집합을 abstraction(중복되는 item이 없고, 순서가 의미가 없음). mutable임.
    • frozenset : immutable set에 해당.
  • Dictionary Type (or Mapping Type)
    • dict : key 와 value로 구성된 pair를 item으로 가지는 collection. key를 통해 value에 접근 (순서가 의미 없음).
  • None Type
    • None : none, void 등에 해당하는 type.
    • "없다"라는 것을 나타낸다.
  • Binary Type
    • bytes: immutable byte sequence. binary data를 위한 tuple이라고 생각하면 쉬움 (하나의 item이 1byte에 해당).
    • bytearray: mutable byte sequence. binary data를 위한 list라고 생각하면 됨.

https://dsaint31.tistory.com/569#Sequence

 

[Math] Sequence (수열) and Series (급수)

Sequence수열, 열 이라고 불림.numbers나 objects 들이 순서를 가지고(ordered) 나열된 것을 가리킴.order(순서)가 의미를 가지며, (order가 다르기 때문에 )중복이 허용이 된다.대표적인 예로 arithmetic sequence(

dsaint31.tistory.com

 

https://ds31x.tistory.com/199

 

[Python] mutable and immutable: Mutability

MutabilityPython에서 Data Types를 구분짓는 중요 속성. Python에서 Object 는id,type,value,reference count를 가지는데,이 중 value를 변경할 수 있는지를 나타내는 것이 바로 mutability임. Mutable인 type의 object(객체)는

ds31x.tistory.com


4-1. Numeric Type

arithmetic operator들과 함께 수를 처리하기 위한 type.

더보기

2022.08.31 - [.../Math] - [Math] 수(Number)의 종류

 

[Math] 수(Number)의 종류

Number의 종류는 다음과 같고, 이들은 각각 set 을 이룸.2024.02.25 - [.../Math] - [Math] Class: set and proper class (클래스와 집합) [Math] Class: set and proper class (클래스와 집합)Class, Proper Class, and SetClass집합론 (Zer

dsaint31.tistory.com

 

https://dsaint31.me/mkdocs_site/CE/ch01/positive_number/#2-for-human

 

BME

양의 정수 표현하기 컴퓨터에서는 대부분 base-2 system (이진수)를 이용하여 positive integer를 표시함. (이 문서에서 positive integer는 0을 포함한 것으로 생각할 것.) 보다 많은 bit가 할당된 경우, 보다

dsaint31.me

 

https://dsaint31.me/mkdocs_site/CE/ch01/real_number/

 

BME

IEEE754 Scientific Notation Significant Figures double float Real Number 이진수로 decimal number(소수점이 있는 수) 표현하기 실수(real number)를 bit로 표현하는 방법을 알기 이전에 2진수로 소수를 표현할 수 있어야

dsaint31.me

 

2022.12.28 - [Computer/CE] - [CE] Float 표현하기 : IEEE754

 

[CE] Float 표현하기 : IEEE754

실수 (Real Number) Representation과학이나 공학분야에서는 real number를 다룰 때, 아주 큰 값이나 아주 작은 값 등의 매우 큰 범위의 수를 다루는 경우가 많음.Real umber(실수)는 사람의 계산에선 주로 분수

dsaint31.tistory.com

 

2022.09.22 - [Computer/ETC] - Round-off Error vs. Truncation Error

 

Round-off Error vs. Truncation Error

Round-off Error: 컴퓨터에서 수치를 저장하는 데이터 타입의 한계로 인한 에러.제한된 비트에 수치를 저장하기 때문에 발생하며 Finite word-length effect, Finite word-length error라고도 불림.주로 quantization에

dsaint31.tistory.com


>>> i = int('7') # '7'이라는 문자열에 해당하는 integer (int type, 정수) 변수 i.
>>> type(i)      # class int임을 확인할 수 있음.
<class 'int'>
>>> i
7

>>> f = 7.4      # float type
>>> type(f)
<class 'float'>
>>> f = 1.       # 1. 은 1.0 과 같이 float type
>>> type(f)
<class 'float'>

>>> c = 1+2j     # complex type
>>> type(c)
<class 'complex'>

 

Python에서 numeric type은 C, C++과 달리 boxed type임. (primitive data type이라는 개념이 python에선 없음)

>>> 7.0.__str__()
'7.0'
  • int 와 float type의 literal 도 자신의 값을 나타내는 문자열을 반환하는 method를 가지고 있음. 
더보기

2023.02.01 - [Programming] - [Programming] Primitive Data Type : C, C++, NumPy, Torch

 

[Programming] Primitive Data Type : C, C++, NumPy, Torch

Primitive Data Type이(Unboxed type)란?C, C++, NumPy, PyTorch, TensorFlow 등에서 사용되는numeric data type들은보통 unboxed type 이라고도 불리는 primitive data type들이다.unboxed type에서는할당된 메모리 bit들이 해당 numeri

dsaint31.tistory.com



4-2. Boolean Type

if statement, while statement 및 logical operator들과 자주 사용되는 type.

  • Boolean Type의 object가 가질 수 있는 value는 단 두가지이며 모두 keywords임.
>>> b = True  # keyword True, False 가 바로 boolean type이 가질 수 있는 값.
>>> type(b)
<class 'bool'>

>>> b = False
>>> type(b)
<class 'bool'>

>>> i = 1
>>> j = 2
>>> b = i<j  or i==j # boolean expression using logical operator
>>> b
True
>>> type(b)
<class 'bool'>

Programming 세계에서 다양한 numeric value에서 0만을 False로 간주하고, 그 외의 수는 True로 간주하는 관례가 있다.

>>> i = 0
>>> b = bool(i)
>>> b
False
>>> f = 8.1
>>> b = bool(f)
>>> b
True

 

다른 type의 object를 boolean type처럼 다루는 경우가 많으며, 이를 truthiness라고 한다. 다음 url을 참고 : 

https://ds31x.blogspot.com/2023/07/python-truthiness.html

 

Python : Truthiness

 

ds31x.blogspot.com

 

boolean algebra와 logical operation에 대한 개념은 다음 url을 참고 :

https://dsaint31.me/mkdocs_site/CE/ch01/ch01_13_boolean_algebra

 

BME228

Boolean Algebra George Boole(1815-1864, 영국)이 고안한 logic을 다루는 algebra로 "True, False를 수학적인 영역으로 포함"시켜 참과 거짓을 1,0에 대입하고, AND, OR, NOT 등의 logical operation을 사용하여 논리적 동작(

dsaint31.me

 


4-3. String Type : str

문자열 (text데이터)을 처리하기 위해 사용되는 type.

 

String (문자열) str의 경우,
character chr의 묶음이며 item들의 순서가 의미가 있다는 점에서 Sequence type에 속하지만,
Text에 대한 abstraction이기 때문에 다양한 문자열 처리를 위한 기능이 많다.
때문에 Collection을 다루는 type들과 공통점을 가지나 문자열 자체를 다루기 위한 기능들을 주의해서 다루어야 함.

  • str의 literal을 표시하기 위해 '(single quote) 나 "(double quote)로 해당 txt를 감싸준다.
  • 단 감싸주는 시작과 끝이 동일한 기호로 이루어져야 함.
  • multi-line의 string은 three single quote 또는 three double quote로 묶어준다. (역시 시작과 끝이 같아야 함.)

다음 예를 확인.

>>> sq = 'single quote'
>>> dq = "double quote"
>>> ml = """multiline
... line1
... line2"""
>>> type(sq)
<class 'str'>
>>> type(dq)
<class 'str'>
>>> type(ml)
<class 'str'>
>>> ml
'multiline\nline1\nline2'
>>> print(ml)
multiline
line1
line2
  • 위의 예에서 \n과 같이 back slash로 시작하는 글자는 escape sequence라고 불리며 특수한 글자들을 표현함.
  • \n은 new line이라고 읽고, string에서 개행을 의미함.

다른 언어에서는 글자 하나만을 다루는 char도 있으나 Python에선 길이가 1인 str 으로 처리함.

a_code = ord('a')   # `a`글자에 해당하는 code 숫자 얻음.
a_chr = chr(a_code) # a_code에 해당하는 글자를 값으로 가지는 변수 a_chr
print(type(a_chr))  # `str` class로 나옴. 즉, 문자열임.

 

https://ds31x.tistory.com/125

 

[Python] String : 문자열

String(문자열)이란?다음 URL에서 4.3. String Type을 참고.https://dsaint31.tistory.com/515 [Python] (Data) Type: Summary1. Type 이란?Programming에서 사용되는 모든 value 혹은 object 들의 종류 를 (data) type이라고 부름.수학

ds31x.tistory.com


4-4. Collection Type

Collection type 은 하나의 이상의 object들을 포함하는 data type을 가리킴.

참고로, 구성하고 있는 각각의 object를 item 또는 element라고 부름.

Sequence type (list, tuple) , Set (set, frozenset), Mapping type (dict) 들은 여러 object들을 묶어놓은(grouping) data type으로서 이들은 모두 Collection type에 속함.

  • Sequence type 중 list는 square bracket을 사용하고 tuple은 parentheses를 사용하며,
  • Set type 중 set은 curly bracket을,
  • Mapping type인 dict는 set과 마찬가지로 curly bracket을 사용하지만 내부의 각 item이 colon으로 구분되는 key and value pair로 구성된다.
>>> l = ['one', 'two', 'three']
>>> type(l)
<class 'list'>
>>> l
['one', 'two', 'three']

>>> t = tuple(l)
>>> type(t)
<class 'tuple'>
>>> t
('one', 'two', 'three')

>>> s = set(l)
>>> s
{'one', 'two', 'three'}

>>> d = {l[0]: 0, l[1]: 1, l[2]: 2}
>>> d
{'one': 0, 'two': 1, 'three': 2}
>>> type(d)
<class 'dict'>
  • list나 tuple은 l[0], t[0]와 같이 item의 순서에 해당하는 index를 square bracket에 기재하여 각 item에 접근이 가능함.
  • dict의 경우는 square bracket 안에 index 대신 key가 들어감. 위의 예에서는 d['one']으로 int 0을 값으로 가지는 item에 접근 가능.
  • set은 수학에서의 집합연산 (union, intersection, 포함여부)에 해당하는 연산과 같이 사용됨.

https://ds31x.tistory.com/34

 

[Python] list (sequence type) : summary

list (Sequence Type) : Summarylist는 ordered mutable collection으로, collection을 위한 python data type들 중 가장 많이 사용된다.C에서의 array와 같이 가장 기본적인 collection임.단, heterogeneous item을 가질 수 있으며,

ds31x.tistory.com

 

https://ds31x.tistory.com/31

 

[Python] dictionary (Mapping type): basic

dictionary (dict)Python에서 dictionary는key-value pair를 item으로 가지는unorderedmutablecollection임: collections.abc.Mapping 의 구현!set과 함께 curly bracket (or brace)를 사용하는데, empty dictionary가 바로 {}로 표현됨(diction

ds31x.tistory.com

 

https://ds31x.tistory.com/33

 

[Python] set and frozenset

set & frozenset set(집합) : 특정 conditions를 만족(=집합에 속함)시키는 구별 가능한(distinct) object의 collection. set의 중요한 수학적 특징은특정 object가 set에 속하는지 아닌지를 명확히 판별(특정 conditions

ds31x.tistory.com

 

2023.07.21 - [.../Math] - [Math] Sequence (수열) and Series (급수)

 

[Math] Sequence (수열) and Series (급수)

Sequence수열, 열 이라고 불림.numbers나 objects 들이 순서를 가지고(ordered) 나열된 것을 가리킴.order(순서)가 의미를 가지며, (order가 다르기 때문에 )중복이 허용이 된다.대표적인 예로 arithmetic sequence(

dsaint31.tistory.com

 


4-5. Binary Data Type for Python

Python에서 Binary data를 byte 단위 (1byte = 8bit)로 다루는데 사용되는 Data Type임.

https://ds31x.tistory.com/182

 

[Python] bytes and bytearray: Binary Data for Python

Python에서 bytes와 bytearray는binary data를 byte 단위 (1byte = 8bit)로 다루는데사용되는 Data Type임.bytes:bytes 는 immutable byte sequence 로서 일종의 byte로 구성된 tuple에 해당 함.byte literal은 다음과 같이 b라는 pre

ds31x.tistory.com

 


참고

  • Python에서는 모든 것이 object이기 때문에 C 나 C++의 primitive data type이 없음.
  • 즉 int type의 모든 object는 해당 type과 관련된 method들을 가진 일종의 class의 instance라고 볼 수 있음.

 

2023.02.01 - [Programming] - [Programming] Primitive Data Type : C, C++, NumPy, Torch

 

[Programming] Primitive Data Type : C, C++, NumPy, Torch

Primitive Data Type이(Unboxed type)란?C, C++, NumPy, Torch, TensorFlow 등에서 사용되는 numeric data type들은보통 unboxed type이라고도 불리는 primitive data type들이다.unboxed type에서는할당된 메모리 bit들이 해당 numeric

dsaint31.tistory.com

Python이 dynamic language이지만, type annotation을 통해 보다 엄격하게 type을 고려한 프로그래밍이 가능함.

https://ds31x.tistory.com/73

 

[Python] Type Annotation: 파이썬에서 변수 및 함수에 type 지정.

Python은 Dynamic language이기 때문에 variable은 여러 type object를 가르킬 수 있다.이는 매우 높은 유연성을 제공해주고, 작은 규모의 소스코드에서는 잘 동작한다. (특히 type에 대해 자유롭다보니 언어

ds31x.tistory.com

2023.06.11 - [Programming] - [Python] Dynamic Language vs. Static Language

 

[Python] Dynamic Typed Language vs. Static Typed Language

Python은 대표적인 dynamic (typed) langauge 이다. (dynamic language는 대부분 interpreter language 임.) 좀 더 엄밀하게 애기하면,Dynamic Language란 특정 동작이나 사항들이 runtime(실행 시간)에 결정되는 특징을 가

dsaint31.tistory.com


 

728x90

'Programming' 카테고리의 다른 글

[Python] Variable (and Object)  (0) 2023.06.13
[Python] Arithmetic in Python and Augmented Assignment  (0) 2023.06.12
[Python] Expression vs. Statement  (0) 2023.06.12
[WSL] Install WSL (Windows Subsystem for Linux)  (0) 2023.06.12
[Python] Python 소개?  (0) 2023.06.12
'Programming' 카테고리의 다른 글
  • [Python] Variable (and Object)
  • [Python] Arithmetic in Python and Augmented Assignment
  • [Python] Expression vs. Statement
  • [WSL] Install WSL (Windows Subsystem for Linux)
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (784)
      • Private Life (14)
      • Programming (55)
        • DIP (116)
        • ML (34)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (368)
        • Signals and Systems (115)
        • Math (176)
        • Linear Algebra (33)
        • Physics (43)
        • 인성세미나 (1)
      • 정리필요. (61)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (7)
        • PET Study 2009 (1)
        • 방사선 장해방호 (5)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    ML
    signals_and_systems
    Programming
    Probability
    function
    SS
    math
    opencv
    random
    Python
    Term
    fourier transform
    signal_and_system
    cv2
    인허가제도
    Vector
    linear algebra
    numpy
    Optimization
    SIGNAL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] (Data) Type: Summary
상단으로

티스토리툴바