diff options
author | 2023-09-01 11:26:55 +0200 | |
---|---|---|
committer | 2023-09-01 09:26:55 +0000 | |
commit | 78577b36141398c0a1d9c57a71e9a0e78758b43f (patch) | |
tree | f268172f10c197766d30a0df271836e10ba4c46c | |
parent | Improve the `repl` tag (#2736) (diff) |
Improve the `in-place` tag (#2737)
* Rewrite the in-place tag
* Fix typo: extra newline
-rw-r--r-- | bot/resources/tags/in-place.md | 36 |
1 files changed, 20 insertions, 16 deletions
diff --git a/bot/resources/tags/in-place.md b/bot/resources/tags/in-place.md index e2218a7df..b66c9d93a 100644 --- a/bot/resources/tags/in-place.md +++ b/bot/resources/tags/in-place.md @@ -1,22 +1,26 @@ --- embed: - title: "Out of place and in place" + title: "In-place vs. Out-of-place operations" --- -In programming, there are two types of operations: "out of place" operations create a new object, leaving the original object unchanged. "in place" operations modify the original object without creating a new one, and return `None` explicitly. +In programming, there are two types of operations: +- "In-place" operations, which modify the original object +- "Out-of-place" operations, which returns a new object and leaves the original object unchanged -A common example of these different concepts is seen in the use of the methods `list.sort()` and `sorted(...)`. Using `list.sort()` and attempting to access an element of the list will result in an error. - -```py -# WRONG: - -unsorted_list = [3, 1, 2] -sorted_list = unsorted_list.sort() # This will be None -print(sorted_list) # Outputs None. Where did the list go? - -list_to_sort = [3, 1, 2] -sorted(list_to_sort) -print(list_to_sort) # The list still isn't sorted. Why? +For example, the `.sort()` method of lists is in-place, so it modifies the list you call `.sort()` on: +```python +>>> my_list = [5, 2, 3, 1] +>>> my_list.sort() # Returns None +>>> my_list +[1, 2, 3, 5] ``` - -To avoid these errors and unexpected results, you should either use an out-of-place operation `(sorted(...))` and assign it to a variable or use an in-place operation `(list.sort())` without assignment. +On the other hand, the `sorted()` function is out-of-place, so it returns a new list and leaves the original list unchanged: +```python +>>> my_list = [5, 2, 3, 1] +>>> sorted_list = sorted(my_list) +>>> sorted_list +[1, 2, 3, 5] +>>> my_list +[5, 2, 3, 1] +``` +In general, methods of mutable objects tend to be in-place (since it can be expensive to create a new object), whereas operations on immutable objects are always out-of-place (since they cannot be modified). |