Home >Backend Development >Python Tutorial >How Can I Efficiently Partition a List Based on a Condition?

How Can I Efficiently Partition a List Based on a Condition?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 16:23:20345browse

How Can I Efficiently Partition a List Based on a Condition?

Partitioning Lists Based on Conditions

When splitting a list into two based on a given condition, it's tempting to iterate over the list twice, creating two new lists as follows:

good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]

However, this approach requires two separate iterations over the list, which can be inefficient. To improve performance, consider using a manual iteration with conditional appending:

good, bad = [], []
for x in mylist:
    (bad, good)[x in goodvals].append(x)

In this code:

  • We initialize two empty lists, good and bad, to store the partitioned elements.
  • We iterate over the elements of mylist.
  • For each element x, we use the expression (bad, good)[x in goodvals] to select the appropriate list based on the condition x in goodvals.
  • This expression evaluates to bad if x does not meet the condition and good otherwise.
  • We append x to the selected list using the append method.

This approach avoids the need for two separate iterations, improving performance by reducing the number of list traversals from two to one. It is also considered more elegant, as it captures the partitioning logic in a concise and readable manner.

The above is the detailed content of How Can I Efficiently Partition a List Based on a Condition?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn