This post is part of a series that summarised a workshop we ran recently. We were discussing programming, discussing common pitfalls, and then looked at some fun python tricks.
There are several sections:
In Python, variables can hold different types of data, and these types can be broadly categorized into two groups: immutable and mutable. The distinction between them is related to whether the data stored in the variable can be changed after creation.
Common examples of immutable types in Python include:
int
)float
)str
)tuple
)frozenset
)Example:
x = 5y = x # y points to the same value as xx = 10 # Creates a new object with the value 10, y still holds 5
Common examples of mutable types in Python include:
list
)dict
)set
)Example:
list1 = [1, 2, 3]list2 = list1 # list2 points to the same list as list1list1.append(4) # Modifies the existing list, list2 also reflects the change
It's important to understand the difference between immutable and mutable types because it affects how you work with data in Python. Immutable objects are often used for things like keys in dictionaries and elements in sets, where the value shouldn't change once added. Mutable objects are useful when you need to modify or update data structures over time, but they require more careful consideration to avoid unexpected behavior.
Remember that some types, like lists, can contain both mutable and immutable elements. For example, you can have a list of integers (immutable) inside a list (mutable). This adds another layer of complexity when working with nested data structures.
Why make this complicated? Why can't everything be immutable then? Well, for one, Immutable types are designed for efficient memory management and better speed.
Questions or comments? @ me on Mastodon @happykhan@mstdn.science or Twitter @happy_khan
The banner image is an AI generated picture (Midjourney) with prompt; 'computer programming in the style of Robert Motherwell'. You can share and adapt this image following a CC BY-SA 4.0 licence.