techmore.in

Python - Data Types

What Are Data Types?

Data types classify the type of data a variable holds. Python is a dynamically typed language, so you don't need to declare the data type explicitly.

Why Use Data Types?

  • They help the interpreter allocate memory efficiently.
  • They define what operations can be performed on a value.
  • They help detect bugs and errors during program execution.

How to Use Data Types?

You can assign any value to a variable and Python will automatically interpret its data type:

python
# This is how you declare variables in Python x = 5 # Integer y = 3.14 # Float name = "Alice" # String is_active = True # Boolean fruits = ["apple", "banana", "cherry"] # List coordinates = (10.0, 20.0) # Tuple unique_ids = {1, 2, 3} # Set person = {"name": "Bob", "age": 30}# Dictionary result = None# NoneType

Built-in Data Types

  • Numeric Types: int, float, complex
  • Text Type: str
  • Sequence Types: list, tuple, range
  • Set Types: set, frozenset
  • Mapping Type: dict
  • Boolean Type: bool
  • Binary Types: bytes, bytearray, memoryview
  • None Type: NoneType

Type Checking

Use type() to check the type of a variable.

python
x = 10 print(type(x)) # <class 'int'>

Type Casting

You can convert between data types using constructor functions:

python
x = int("5") # string to int y = float(10) # int to float z = str(3.14) # float to string

What are Immutable Data Types?

Immutable objects are those that cannot be changed after their creation. Any modification to them results in a new object being created.

Immutable data types include: int, float, bool, str, tuple, frozenset, bytes.

python
# Example of Immutable data type a = 10 print(id(a)) a += 1 # Creates a new object print(id(a))

What are Mutable Data Types?

Mutable objects can be changed after their creation without creating a new object. They support in-place updates.

Mutable data types include: list, dict, set, bytearray, user-defined classes.

python
# Example of Mutable data type lst = [1, 2, 3] print(id(lst)) lst.append(4) # Modified in-place print(id(lst))

Why is this important?

  • Performance: Immutable objects can be optimized by Python’s memory model.
  • Hashability: Only immutable types can be used as dictionary keys or set elements.
  • Predictability: Mutable objects shared between scopes can lead to bugs if modified unintentionally.

How to choose?

Choose immutable types for data that shouldn’t change (e.g., configuration values, constants). Use mutable types when the structure needs to be updated or extended frequently.

python
# Using mutable inside immutable (tuple with a list) t = (1, 2, [3, 4]) t[2].append(5) print(t) # This works!