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:
Common examples of mutable types in Python include:
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.
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.