Data Types in Python
Python has several built-in data types, broadly grouped as:
| Category | Types |
|---|---|
| Numeric | int, float, complex |
| Sequence | str, list, tuple, range |
| Mapping | dict |
| Set | set, frozenset |
| Boolean | bool |
| Binary | bytes, bytearray, memoryview |
| None | NoneType |
Numeric Types
a = 10 # int — whole numbers
b = 3.14 # float — decimal numbers
c = 2 + 3j # complex — real + imaginary part
print(type(a), type(b), type(c))
Boolean
flag = True
print(type(flag)) # <class 'bool'>
print(True + True) # 2 -> bool is a subtype of int
Sequence Types
s = "Python" # str — ordered, immutable characters
lst = [1, 2, 3] # list — ordered, mutable
tup = (1, 2, 3) # tuple — ordered, immutable
r = range(5) # range — sequence of numbers
Mapping Type
d = {"name": "Ravi", "age": 21} # dict — key-value pairs
Set Types
st = {1, 2, 3} # set — unordered, unique, mutable
fs = frozenset({1, 2, 3}) # frozenset — unordered, unique, immutable
None Type
x = None
print(type(x)) # <class 'NoneType'>
Type Conversion (Casting)
print(int("25")) # 25 (str -> int)
print(float(10)) # 10.0 (int -> float)
print(str(3.14)) # '3.14' (float -> str)
print(list("abc")) # ['a', 'b', 'c']
print(bool(0)) # False
print(bool(1)) # True
type() and isinstance()
x = 5
print(type(x) == int) # True
print(isinstance(x, int)) # True (preferred, supports inheritance)