From c1f9a492009c4a6fcab36feeeb0aae2f649e81d5 Mon Sep 17 00:00:00 2001 From: Terry Jan Reedy Date: Tue, 29 Sep 2020 01:02:44 -0400 Subject: [PATCH] bpo-41774: Add programming FAQ entry (GH-22402) In the "Sequences (Tuples/Lists)" section, add "How do you remove multiple items from a list". (cherry picked from commit 5b0181d1f6474c2cb9b80bdaf3bc56a78bf5fbe7) Co-authored-by: Terry Jan Reedy --- Doc/faq/programming.rst | 15 +++++++++++++++ .../2020-09-24-15-35-13.bpo-41774.5IqdGP.rst | 2 ++ 2 files changed, 17 insertions(+) create mode 100644 Misc/NEWS.d/next/Documentation/2020-09-24-15-35-13.bpo-41774.5IqdGP.rst diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst index 70e9190e5a5205..1af04483eb3294 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -1163,6 +1163,21 @@ This converts the list into a set, thereby removing duplicates, and then back into a list. +How do you remove multiple items from a list +-------------------------------------------- + +As with removing duplicates, explicitly iterating in reverse with a +delete condition is one possibility. However, it is easier and faster +to use slice replacement with an implicit or explicit forward iteration. +Here are three variations.:: + + mylist[:] = filter(keep_function, mylist) + mylist[:] = (x for x in mylist if keep_condition) + mylist[:] = [x for x in mylist if keep_condition] + +If space is not an issue, the list comprehension may be fastest. + + How do you make an array in Python? ----------------------------------- diff --git a/Misc/NEWS.d/next/Documentation/2020-09-24-15-35-13.bpo-41774.5IqdGP.rst b/Misc/NEWS.d/next/Documentation/2020-09-24-15-35-13.bpo-41774.5IqdGP.rst new file mode 100644 index 00000000000000..af8e02437cb2b5 --- /dev/null +++ b/Misc/NEWS.d/next/Documentation/2020-09-24-15-35-13.bpo-41774.5IqdGP.rst @@ -0,0 +1,2 @@ +In Programming FAQ "Sequences (Tuples/Lists)" section, add "How do you +remove multiple items from a list".