Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *