Intern
What are the two main data types in Python that you know?
sobes.tech AI
Answer from AI
Python has many built-in data types, but the two main, often contrasted, are mutable and immutable types.
Mutable types can be modified after creation.
Immutable types cannot be changed after creation. Any operation that "changes" an immutable object actually creates a new object.
Examples:
| Mutable | Immutable |
|---|---|
list |
int |
dict |
float |
set |
str |
bytearray |
tuple |
objects (classes) |
bool |
NoneType |
|
bytes |
Example of changing a mutable type (list):
# Create a list
my_list = [1, 2, 3]
# Modify an element of the list
my_list[0] = 10
# Now my_list is [10, 2, 3] - the same object was modified
Example of "changing" an immutable type (tuple):
# Create a tuple
my_tuple = (1, 2, 3)
# Attempting to change an element will cause an error
# my_tuple[0] = 10 # TypeError: 'tuple' object does not support item assignment
# Creating a new tuple from the existing one
new_tuple = (10,) + my_tuple[1:]
# Now new_tuple = (10, 2, 3), but my_tuple remains (1, 2, 3).
# A new object new_tuple was created, my_tuple remains unchanged
This difference is important when working with functions (mutable objects can be changed "in place" inside a function, affecting the original object), when used as dictionary keys (only immutable objects can be keys), and in multithreading (mutable objects require more careful handling).