aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar kwzrd <[email protected]>2020-05-17 12:22:18 +0100
committerGravatar GitHub <[email protected]>2020-05-17 12:22:18 +0100
commita77b67c6a4ae0a4f1241d988499d17beb08d84c1 (patch)
tree323e691010e6ab0ebb3b3cc6f57c78eca4867a01
parentMerge pull request #949 from python-discord/help-command-fix-invocation (diff)
parentMerge branch 'master' into decorator-factory-mutability-tag (diff)
Merge pull request #858 from python-discord/decorator-factory-mutability-tag
Add mutability.md tag
-rw-r--r--bot/resources/tags/mutability.md37
1 files changed, 37 insertions, 0 deletions
diff --git a/bot/resources/tags/mutability.md b/bot/resources/tags/mutability.md
new file mode 100644
index 000000000..bde9b5e7e
--- /dev/null
+++ b/bot/resources/tags/mutability.md
@@ -0,0 +1,37 @@
+**Mutable vs immutable objects**
+
+Imagine that you want to make all letters in a string upper case. Conveniently, strings have an `.upper()` method.
+
+You might think that this would work:
+```python
+>>> greeting = "hello"
+>>> greeting.upper()
+'HELLO'
+>>> greeting
+'hello'
+```
+
+`greeting` didn't change. Why is that so?
+
+That's because strings in Python are _immutable_. You can't change them, you can only pass around existing strings or create new ones.
+
+```python
+>>> greeting = "hello"
+>>> greeting = greeting.upper()
+>>> greeting
+'HELLO'
+```
+
+`greeting.upper()` creates and returns a new string which is like the old one, but with all the letters turned to upper case.
+
+`int`, `float`, `complex`, `tuple`, `frozenset` are other examples of immutable data types in Python.
+
+Mutable data types like `list`, on the other hand, can be changed in-place:
+```python
+>>> my_list = [1, 2, 3]
+>>> my_list.append(4)
+>>> my_list
+[1, 2, 3, 4]
+```
+
+Other examples of mutable data types in Python are `dict` and `set`. Instances of user-defined classes are also mutable.