본문으로 건너뛰기

Python 데이터 타입 확인, 비교

파이썬에서 어떤 객체(데이터, 자료형)의 Type이 궁금할 때, 타입을 직접 확인해볼 수 있습니다. 또한 객체의 타입이 어떤 타입과 같은지 비교할 수도 있습니다.

1. type()으로 변수의 type 체크

type(object)는 인자로 전달된 object의 타입을 리턴합니다.

아래와 같이 다양한 자료형의 타입을 확인할 수 있습니다.

print(type(12345))

print(type(123.45))

print(type('string'))

my_list = ['a', 'b', 'c', 'd']
print(type(my_list))

my_tuple = ('1', '2', '3')
print(type(my_tuple))

my_dict = {1: '1', 2: '2', 3: '3'}
print(type(my_dict))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>

2. if와 type()으로 변수의 type 비교

type(object) is type은 object의 타입이 인자로 전달된 type과 같을 때 true가 됩니다.

아래와 같이 if와 type()를 이용하여 타입 비교를 할 수 있습니다.

if type(123) is int:
print("It's int")

if type(123.4) is float:
print("It's float")

if type('str') is str:
print("It's str")

my_list = ['a', 'b']
if type(my_list) is list:
print("It's list")

my_dict = {1: '1', 2: '2', 3: '3'}
if type(my_dict) is dict:
print("It's dict")

Output:

It's int
It's float
It's str
It's list
It's dict

3. if와 isinstance()로 변수의 type 비교

isinstance(object, type)는 object의 타입이 인자로 전달된 type과 같을 때 true를 리턴합니다. 또한, object가 type의 subclass일 때도 true가 리턴됩니다.

아래와 같이 if와 isinstance()를 이용하여 타입 비교를 할 수 있습니다.

if isinstance(123, int):
print("It's int")

if isinstance(123.4, float):
print("It's float")

if isinstance('str', str):
print("It's str")

my_list = ['a', 'b']
if isinstance(my_list, list):
print("It's list")

my_dict = {1: '1', 2: '2', 3: '3'}
if isinstance(my_dict, dict):
print("It's dict")

Output:

It's int
It's float
It's str
It's list
It's dict