How to Remove Elements from a List Using List Comprehension in Python?

Estimated read time 1 min read

You can use list comprehension to remove elements from a list based on a certain condition. Here’s an example:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]

In this example, we have a list of numbers (numbers). We want to create a new list (even_numbers) that only contains the even numbers from the original list. We achieve this by using list comprehension. We iterate over each number in numbers and include only those that satisfy the condition num % 2 == 0 (i.e., those that are even).

You can also use list comprehension to remove elements from a list based on a condition. Here’s an example:

numbers = [1, 2, 3, 4, 5, 6]
odd_numbers = [num for num in numbers if num % 2 != 0]
print(odd_numbers) # Output: [1, 3, 5]

In this example, we create a new list (odd_numbers) that only contains the odd numbers from the original list. We use the same list comprehension syntax, but we change the condition to num % 2 != 0 (i.e., those that are odd).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply