Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to separate a Python list into several lists based on the condition of its elements is to use list comprehension and create multiple lists based on the condition. For example, consider the following list:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If we want to create two lists - one with even numbers and one with odd numbers, we can use list comprehension as follows:

even_list = [num for num in my_list if num % 2 == 0]
odd_list = [num for num in my_list if num % 2 != 0]

This will create a new list even_list with elements [2, 4, 6, 8, 10] and a new list odd_list with elements [1, 3, 5, 7, 9] based on the condition of even and odd numbers.

Similarly, we can create multiple lists based on any condition on the elements of the list using list comprehension in Python.