
Python 데이터 타입
Python에서 데이터 타입은 변수에 저장할 수 있는 데이터의 종류를 정의한다. Python은 동적 타이핑 언어이므로 변수를 선언할 때 타입을 명시하지 않아도 되며, 값이 할당될 때 자동으로 타입이 결정된다.
내장 데이터 타입
Python에는 다양한 내장 데이터 타입이 있으며, 각각 고유한 특성과 용도를 가지고 있다.
Python 데이터 타입 분류
분류 | 타입 이름 | 예시 |
---|---|---|
텍스트 | str | “Hello World” |
숫자 | int, float, complex | 20, 20.5, 1j |
시퀀스 | list, tuple, range | [“apple”, “banana”], (1, 2, 3), range(6) |
매핑 | dict | {“name”: “John”, “age”: 36} |
집합 | set, frozenset | {“apple”, “banana”}, frozenset({1, 2}) |
불린 | bool | True, False |
바이너리 | bytes, bytearray, memoryview | b”hello”, bytearray(5) |
None | NoneType | None |
데이터 타입 확인하기
Python에서는 type() 함수를 사용하여 변수의 데이터 타입을 확인할 수 있다.
기본 타입 확인
x = 5
print(type(x))
y = "Hello World"
print(type(y))
z = [1, 2, 3]
print(type(z))
실행 결과는 다음과 같다.
다양한 데이터 타입 예제
# 텍스트 타입text = "Hello World"
print(f"text: {type(text)}")
# 숫자 타입
integer = 20
floating = 20.5
complex_num = 1j
print(f"integer: {type(integer)}")
print(f"floating: {type(floating)}")
print(f"complex: {type(complex_num)}")
# 시퀀스 타입
my_list = ["apple", "banana", "cherry"]
my_tuple = ("apple", "banana", "cherry")
my_range = range(6)
print(f"list: {type(my_list)}")
print(f"tuple: {type(my_tuple)}")
print(f"range: {type(my_range)}")
텍스트 타입 - str
문자열(str)은 텍스트 데이터를 저장하는 데 사용된다.
문자열 생성
name = "John"message = 'Hello World'
multiline = """이것은
여러 줄
문자열입니다"""
print(f"name: {name} (타입: {type(name)})")
print(f"message: {message}")
print(f"multiline:\n{multiline}")
문자열 특성
- 불변(immutable) 객체
- 시퀀스 타입 (인덱싱, 슬라이싱 가능)
- 다양한 내장 메서드 제공
- 유니코드 지원
숫자 타입
Python에는 세 가지 숫자 타입이 있다.
정수 (int)
x = 1y = 35656222554887711
z = -3255522
print(f"x = {x}, 타입: {type(x)}")
print(f"y = {y}, 타입: {type(y)}")
print(f"z = {z}, 타입: {type(z)}")
실수 (float)
x = 1.10y = 1.0
z = -35.59
scientific = 35e3 # 과학적 표기법
print(f"x = {x}, 타입: {type(x)}")
print(f"scientific = {scientific}, 타입: {type(scientific)}")
복소수 (complex)
x = 3+5jy = 5j
z = -5j
print(f"x = {x}, 타입: {type(x)}")
print(f"y = {y}, 타입: {type(y)}")
print(f"z = {z}, 타입: {type(z)}")
시퀀스 타입
시퀀스 타입은 순서가 있는 데이터 컬렉션이다.
리스트 (list)
리스트는 순서가 있고 변경 가능한 컬렉션이다.
fruits = ["apple", "banana", "cherry"]numbers = [1, 5, 7, 9, 3]
mixed = [1, "Hello", 3.4, True]
print(f"fruits: {fruits}, 타입: {type(fruits)}")
print(f"numbers: {numbers}")
print(f"mixed: {mixed}")
# 리스트 수정 가능
fruits[1] = "orange"
print(f"수정된 fruits: {fruits}")
튜플 (tuple)
튜플은 순서가 있고 변경 불가능한 컬렉션이다.
coordinates = (10, 20)colors = ("red", "green", "blue")
single_item = ("apple",) # 단일 요소 튜플
print(f"coordinates: {coordinates}, 타입: {type(coordinates)}")
print(f"colors: {colors}")
print(f"single_item: {single_item}")
# 튜플은 수정 불가능
# colors[0] = "yellow" # TypeError 발생
범위 (range)
range는 숫자 시퀀스를 나타낸다.
numbers = range(6)custom_range = range(2, 10, 2)
print(f"numbers: {list(numbers)}, 타입: {type(numbers)}")
print(f"custom_range: {list(custom_range)}")
# range 활용
for i in range(5):
print(f"숫자: {i}")
매핑 타입 - dict
딕셔너리는 키-값 쌍으로 데이터를 저장하는 매핑 타입이다.
person = {"name": "John",
"age": 36,
"country": "Norway"
}
empty_dict = {}
print(f"person: {person}, 타입: {type(person)}")
print(f"이름: {person['name']}")
print(f"나이: {person['age']}")
# 딕셔너리 수정
person["city"] = "Oslo"
print(f"수정된 person: {person}")
집합 타입
집합은 중복되지 않는 요소들의 컬렉션이다.
집합 (set)
fruits = {"apple", "banana", "cherry"}numbers = {1, 2, 3, 4, 5}
print(f"fruits: {fruits}, 타입: {type(fruits)}")
print(f"numbers: {numbers}")
# 중복 요소 자동 제거
duplicates = {1, 2, 2, 3, 3, 4}
print(f"중복 제거된 집합: {duplicates}")
# 집합 연산
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(f"합집합: {set1 | set2}")
print(f"교집합: {set1 & set2}")
print(f"차집합: {set1 - set2}")
불변 집합 (frozenset)
frozen = frozenset([1, 2, 3, 4])print(f"frozen: {frozen}, 타입: {type(frozen)}")
# frozenset은 수정 불가능
# frozen.add(5) # AttributeError 발생
불린 타입 - bool
불린 타입은 True 또는 False 값을 가진다.
is_student = Trueis_adult = False
print(f"is_student: {is_student}, 타입: {type(is_student)}")
print(f"is_adult: {is_adult}, 타입: {type(is_adult)}")
# 불린 연산
result = is_student and not is_adult
print(f"연산 결과: {result}")
# 다른 타입의 불린 변환
print(f"bool(1): {bool(1)}")
print(f"bool(0): {bool(0)}")
print(f"bool('hello'): {bool('hello')}")
print(f"bool(''): {bool('')}")
print(f"bool([]): {bool([])}")
print(f"bool([1, 2]): {bool([1, 2])}")
None 타입
None은 값이 없음을 나타내는 특별한 상수다.
x = Noneprint(f"x: {x}, 타입: {type(x)}")
# None 활용
def get_user_name():
# 사용자를 찾지 못한 경우
return None
user = get_user_name()
if user is None:
print("사용자를 찾을 수 없습니다")
# None과 False의 차이
print(f"None == False: {None == False}")
print(f"None is False: {None is False}")
print(f"bool(None): {bool(None)}")
바이너리 타입
바이너리 데이터를 다루기 위한 타입들이다.
bytes
data = b"hello"encoded = "안녕하세요".encode('utf-8')
print(f"data: {data}, 타입: {type(data)}")
print(f"encoded: {encoded}, 타입: {type(encoded)}")
# bytes는 불변
# data[0] = 72 # TypeError 발생
bytearray
mutable_bytes = bytearray(b"hello")print(f"mutable_bytes: {mutable_bytes}, 타입: {type(mutable_bytes)}")
# bytearray는 가변
mutable_bytes[0] = 72 # 'h'를 'H'로 변경
print(f"수정된 bytearray: {mutable_bytes}")
타입 변환 (Type Casting)
한 데이터 타입을 다른 타입으로 변환할 수 있다.
기본 타입 변환
# 문자열을 숫자로str_num = "123"
int_num = int(str_num)
float_num = float(str_num)
print(f"원본: {str_num} ({type(str_num)})")
print(f"정수: {int_num} ({type(int_num)})")
print(f"실수: {float_num} ({type(float_num)})")
# 숫자를 문자열로
number = 456
str_from_int = str(number)
print(f"숫자에서 문자열: {str_from_int} ({type(str_from_int)})")
# 리스트와 튜플 변환
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
back_to_list = list(my_tuple)
print(f"리스트: {my_list}")
print(f"튜플: {my_tuple}")
print(f"다시 리스트: {back_to_list}")
안전한 타입 변환
def safe_int_convert(value):"""안전한 정수 변환 함수"""
try:
return int(value)
except ValueError:
print(f"'{value}'를 정수로 변환할 수 없습니다")
return None
# 테스트
print(safe_int_convert("123")) # 123
print(safe_int_convert("abc")) # None
print(safe_int_convert("12.34")) # ValueError 발생
타입 검사
변수의 타입을 확인하는 다양한 방법이 있다.
isinstance() 함수
x = 5y = "Hello"
z = [1, 2, 3]
print(f"x는 int인가? {isinstance(x, int)}")
print(f"y는 str인가? {isinstance(y, str)}")
print(f"z는 list인가? {isinstance(z, list)}")
# 여러 타입 확인
print(f"x는 (int, float) 중 하나인가? {isinstance(x, (int, float))}")
# 상속 관계도 고려
print(f"True는 int인가? {isinstance(True, int)}") # True (bool은 int의 서브클래스)
hasattr() 함수
class Person:def __init__(self, name):
self.name = name
def greet(self):
return f"안녕하세요, {self.name}입니다"
person = Person("홍길동")
print(f"person에 name 속성이 있는가? {hasattr(person, 'name')}")
print(f"person에 greet 메서드가 있는가? {hasattr(person, 'greet')}")
print(f"person에 age 속성이 있는가? {hasattr(person, 'age')}")
가변성과 불변성
Python 객체는 가변(mutable)과 불변(immutable)으로 구분된다.
불변 객체
# 불변 객체들immutable_types = [
42, # int
3.14, # float
"hello", # str
(1, 2, 3), # tuple
frozenset([1, 2, 3]) # frozenset
]
for obj in immutable_types:
print(f"{obj} ({type(obj).__name__}): 불변 객체")
# 문자열 수정 시도
text = "hello"
# text[0] = "H" # TypeError: 'str' object does not support item assignment
가변 객체
# 가변 객체들my_list = [1, 2, 3]
my_dict = {"a": 1, "b": 2}
my_set = {1, 2, 3}
print("가변 객체 수정:")
my_list.append(4)
print(f"리스트 수정: {my_list}")
my_dict["c"] = 3
print(f"딕셔너리 수정: {my_dict}")
my_set.add(4)
print(f"집합 수정: {my_set}")
💡 데이터 타입 선택 가이드:
• 순서가 중요하고 수정이 필요하면 리스트 사용
• 순서가 중요하지만 수정이 불필요하면 튜플 사용
• 키-값 매핑이 필요하면 딕셔너리 사용
• 중복 제거와 집합 연산이 필요하면 set 사용
• 성능이 중요한 경우 적절한 타입 선택 고려
실무 활용 예제
다양한 데이터 타입을 활용한 실무 예제들이다.
학생 성적 관리 시스템
# 학생 정보를 다양한 데이터 타입으로 관리students = [
{
"name": "홍길동",
"age": 20,
"grades": [85, 92, 78],
"subjects": ("수학", "영어", "과학"),
"is_scholarship": True,
"contact": None
},
{
"name": "김영희",
"age": 19,
"grades": [95, 87, 91],
"subjects": ("수학", "영어", "과학"),
"is_scholarship": False,
"contact": "kim@email.com"
}
]
for student in students:
name = student["name"]
average = sum(student["grades"]) / len(student["grades"])
status = "장학생" if student["is_scholarship"] else "일반학생"
contact = student["contact"] if student["contact"] else "연락처 없음"
print(f"학생: {name}")
print(f"평균: {average:.1f}점")
print(f"상태: {status}")
print(f"연락처: {contact}")
print("-" * 20)
데이터 분석 예제
# 판매 데이터 분석sales_data = {
"products": ["노트북", "마우스", "키보드", "모니터"],
"quantities": [10, 50, 30, 15],
"prices": [1200000, 25000, 80000, 300000],
"categories": {"노트북", "주변기기", "주변기기", "주변기기"}
}
# 총 매출 계산
total_revenue = 0
for i in range(len(sales_data["products"])):
product = sales_data["products"][i]
quantity = sales_data["quantities"][i]
price = sales_data["prices"][i]
revenue = quantity * price
total_revenue += revenue
print(f"{product}: {quantity}개 × {price:,}원 = {revenue:,}원")
print(f"\n총 매출: {total_revenue:,}원")
print(f"판매 카테고리: {sales_data['categories']}")
Python의 다양한 데이터 타입을 이해하고 적절히 활용하면 효율적이고 읽기 쉬운 코드를 작성할 수 있다. 각 타입의 특성을 파악하고 상황에 맞는 타입을 선택하는 것이 중요하다.