Skip to content

Commit 2211bda

Browse files
feat: remove_elements_list - Remove elements not matching certain pattern - the fast way
1 parent c96f249 commit 2211bda

File tree

6 files changed

+22
-0
lines changed

6 files changed

+22
-0
lines changed

ebook/chapters/standard_lib_chapters/lists.tex

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,16 @@ \subsection{Unpacking Lists Using * Operator}
6565
b = [2, 3, 4]
6666
c = 5
6767
\end{lstlisting}
68+
69+
70+
\subsection{Remove Elements Not Matching Pattern}
71+
72+
Let's assume you have a list of certain data and want to remove all elements in it, which are not matching a certain pattern.
73+
You could make use of the built-in \lstinline{list.remove()} method, which removes the first match of and then shifts all subsequent data one position to the left.
74+
So, if you want to remove all, you need to loop over it.
75+
However, this approach gives quadratic behaviour.
76+
The following Listing shows you a much better way to achieve this:
77+
78+
\lstinputlisting[caption=remove\_elements\_list.py]{../standard_lib/remove_elements_list.py}
79+
80+
This approach is not only faster, but creates a new, distinct list and then replaces the old contents all at once.

ebook/python-snippets.epub

474 Bytes
Binary file not shown.

ebook/python-snippets.mobi

1.3 KB
Binary file not shown.

ebook/python-snippets.pdf

1.84 KB
Binary file not shown.

standard_lib/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ A collection of useful snippets using only the standard library.
4848
| reduce_memory_consumption_iterator | Shows how to reduce memory consumption by using itertools.repeat |
4949
| regular_expression_debug | Display debug information about the compiled regular expression with re.DEBUG flag |
5050
| remove_duplicates_list | Remove duplicates from list and keep the order |
51+
| remove_elements_list | Remove elements not matching certain pattern - the fast way! |
5152
| save_dict_update_without_loosing_original | Update dict value without loosing original value |
5253
| scopes_namespaces | Reveils the differences between `global`, `local`, and `nonlocal` |
5354
| set_union_intersection | Use \| and & for set union and intersection |
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
data = [1, 2, 3, 4, 1, 2, 3, 4]
2+
target = 1
3+
4+
print(f"Original: {data}")
5+
6+
data[:] = [elem for elem in data if elem != target]
7+
8+
print(f"New: {data}")

0 commit comments

Comments
 (0)