Intern
What is the difference between data types in Python?
sobes.tech AI
Answer from AI
In Python, data types define what operations can be performed on values and how they are stored in memory. The main types are divided into mutable and immutable.
Mutable types:
list: An ordered collection of elements that can be modified after creation.dict: An unordered collection of key-value pairs, keys must be hashable, and it can be modified.set: An unordered collection of unique elements, can be modified.bytearray: A mutable sequence of integers from 0 to 255.
Immutable types:
int: Whole numbers.float: Floating-point numbers.str: A sequence of characters, immutable.tuple: An ordered collection of elements, immutable after creation.frozenset: An unordered collection of unique elements, immutable.bytes: An immutable sequence of integers from 0 to 255.
Main differences:
- Changing values: Mutable objects can be changed in-place, whereas immutable objects create a new copy when modified.
- Performance: Modifying mutable objects is usually faster because it does not require creating a new object. Immutable objects can be optimized by Python for reuse (interning).
- Using as dictionary keys: Only hashable data types can be used as dictionary keys and set elements. Immutable types (except
bytes) are usually hashable, mutable ones (list,dict,set) are usually not.
Examples:
# Mutable type: list
my_list = [1, 2, 3]
my_list.append(4) # In-place modification
print(my_list) #[1, 2, 3, 4]
# Immutable type: str
my_string = "hello"
# my_string[0] = "H" # Error: 'str' object does not support item assignment
new_string = my_string + " world" # Creates a new str object
print(new_string) #hello world