Menu Close

How to split a list based on a condition with Python?

Sometimes, we want to split a list based on a condition with Python.

In this article, we’ll look at how to split a list based on a condition with Python.

How to split a list based on a condition with Python?

To split a list based on a condition with Python, we can use list comprehension.

For instance, we write

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

to create the good list with the values in the goodvals list with

[x for x in mylist if x in goodvals]

Likewise, we create the bad list with the values that aren’t in goodvals with

[x for x in mylist if x not in goodvals]

Conclusion

To split a list based on a condition with Python, we can use list comprehension.

Posted in Python, Python Answers