Python Data Types

In programming, data types are an important concept. Variables can store data of different types, and different types can perform different operations. Python has multiple built-in data types, mainly classified into the following categories:

Core Data Types

Type NameType AliasExampleDescription
Text Typestr"Hello", 'Python'Used to store text, composed of a series of characters.
Numeric Typeint10, -50Integers.
float3.14, -0.01Floating point numbers (i.e., decimal).
complex1+2jComplex numbers.
Sequence Typelist[1, "apple", 3.0]Lists, ordered and modifiable collections.
tuple(1, "apple", 3.0)Tuples, ordered but immutable collections.
rangerange(6)Represents an immutable numeric sequence.
Mapping Typedict{"name": "John", "age": 30}Dictionaries, unordered key-value pair collections.
Set Typeset{"apple", "banana"}
Frozen Set Typefrozensetfrozenset({"a", "b"})
Boolean TypeboolTrue, FalseRepresents true or false.
Binary Typebytes, bytearray, memoryviewb"Hello"Used to process binary data.
None TypeNoneTypeNoneRepresents an empty value or non-existent value.

Getting Variable Type

You can use the built-in type() function to check the data type of any variable.

x = 5
y = "Hello, World!"
z = [1, 2, 3]

print(type(x))  # Output: <class 'int'>
print(type(y))  # Output: <class 'str'>
print(type(z))  # Output: <class 'list'>

Python is Dynamically Typed

Python is a dynamically typed language. This means you don't need to specify the variable's type when declaring it; the interpreter automatically infers it at runtime. This makes development more flexible and fast.

my_var = 100       # At this point, my_var is int type
print(type(my_var))

my_var = "Now I'm a string"  # Now my_var has become str type
print(type(my_var))

Mutable and Immutable Types

Data types can be classified as mutable or immutable based on whether their values can be changed after creation.

  • Immutable (Mutable): Once created, their values cannot be changed. If you perform a modification on a variable, it actually creates a new object.

    • Includes: int, float, complex, str, tuple, frozenset, bool, bytes
    a = "hello"
    a[0] = 'H'  # This will raise TypeError error because strings are immutable
    a = "world"   # This is not a modification, but rather lets a point to a new string object
  • Mutable (Mutable): After creation, their values can be changed, without needing to create a new object.

    • Includes: list, dict, set, bytearray
    my_list = [1, 2, 3]
    my_list[0] = 99  # Modify directly on the original list
    print(my_list)   # Output: [99, 2, 3]

Understanding the difference between mutable and immutable types is crucial for writing efficient and bug-free Python code.