Python is a dynamically typed language, meaning variables do not need explicit type declarations. Instead, the type is assigned automatically based on the value assigned to a variable. Python provides several built-in data types, categorized broadly into numeric, sequence, set, mapping, boolean, and binary types.
Numeric Types
Numeric data types store numerical values and support mathematical operations.
- int (Integer)
x = 10 y = -200 z = 0
- float (Floating Point Number)
a = 3.14 b = -25.67 c = 1.0 # Even though it looks like an integer, it's a float.
- complex (Complex Numbers)
num1 = 2 + 3j num2 = complex(4, -5) # Equivalent to 4 - 5j
Sequence Types
Sequences store ordered collections of items.
- str (String)
s1 = "Hello, World!" s2 = 'Python' s3 = """This is a multi-line string"""
- list (List)
lst = [10, "apple", 3.14, [1, 2, 3]]
- tuple (Tuple)
tpl = (1, 2, "Python", 3.5)
- range (Range)
r = range(5) # 0, 1, 2, 3, 4 r2 = range(1, 10, 2) # 1, 3, 5, 7, 9
Set Types
Sets store unique, unordered items.
- set (Set)
my_set = {1, 2, 3, 4, 4, 2} # {1, 2, 3, 4}
- frozenset (Immutable Set)
fs = frozenset([1, 2, 3, 4])
Mapping Types
Mapping types store key-value pairs.
- dict (Dictionary)
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
Boolean Type
a = True b = False
Binary Types
Binary data types store raw binary data.
- bytes (Immutable Binary Data)
b = b"Hello"
- bytearray (Mutable Binary Data)
ba = bytearray([65, 66, 67])
- memoryview (Memory Sharing Object)
mv = memoryview(b"abc")
NoneType
x = None
Type Checking & Conversion
Python provides functions to check and convert data types.
- Checking Data Type (type())
print(type(10)) # <class 'int'> print(type("hello")) # <class 'str'>
- Type Conversion (Casting)
x = int("10") # String to int y = float("3.14") # String to float z = str(100) # Int to string l = list("abc") # String to list → ['a', 'b', 'c']
Python provides a rich set of built-in data types, each suited for different scenarios. Understanding these types helps in writing efficient and bug-free code.