Python has several built-in data types that serve different purposes. Here's a comprehensive breakdown:
Numeric Types
Integer (int)
- Whole numbers without decimal points
- Can be positive, negative, or zero
- No size limit (limited only by available memory)
age = 25
temperature = -5
Float (float)
- Numbers with decimal points
- Uses double precision
price = 19.99
pi = 3.14159
Complex (complex)
- Numbers with real and imaginary parts
z = 3 + 4j
Sequence Types
String (str)
- Ordered collection of characters
- Immutable (cannot be changed after creation)
- Enclosed in quotes (single, double, or triple)
name = "Alice"
message = 'Hello World'
multiline = """This is a
multiline string"""
List (list)
- Ordered collection of items
- Mutable (can be modified)
- Can contain different data types
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True]
Tuple (tuple)
- Ordered collection of items
- Immutable
- Defined with parentheses
coordinates = (10, 20)
colors = ("red", "green", "blue")
Mapping Type
Dictionary (dict)
- Unordered collection of key-value pairs
- Keys must be immutable and unique
- Values can be any data type
person = {"name": "John", "age": 30, "city": "New York"}
Set Types
Set (set)
- Unordered collection of unique items
- Mutable
- No duplicate values allowed
unique_numbers = {1, 2, 3, 4, 5}
Frozen Set (frozenset)
- Immutable version of set
immutable_set = frozenset([1, 2, 3, 4])
Boolean Type
Boolean (bool)
- Represents True or False
- Subclass of int (True = 1, False = 0)
is_sunny = True
is_raining = False
None Type
None (NoneType)
- Represents absence of value
- Often used as default value or placeholder
result = None
Key Characteristics
Mutable vs Immutable:
- Mutable: list, dict, set (can be modified)
- Immutable: int, float, str, tuple, frozenset, bool, None (cannot be modified)
Type Checking:
type(42) # <class 'int'>
isinstance(42, int) # True
Type Conversion:
int("123") # 123
str(456) # "456"
list("hello") # ['h', 'e', 'l', 'l', 'o']
Understanding these data types is fundamental since they determine what operations you can perform on your data and how Python stores and manipulates information in memory.
Top comments (0)