top of page

Python (3): List Comprehension




In this article, I'll introduce a simple but effective technique in Python that helps create a new list by filtering out unwanted elements in the original list using condition.



Let's see an example.



nums[:] = [num for num in nums if num != val]
        return nums


The highlighted parts are the syntax of list comprehension with condition check.


Assume nums is a list of integers [2, 0, 3, 5, 6, 4, 3], val is the number that we want to filter out in the list, let's say 3.


The first num in [num for num in nums if num != val] means num is the elements that we want to put in the new list.


It takes the value of the current elements (second num) of nums after condition check.


"for num in nums if num != val" check if the value of each element in nums is not equal to val.


If the current element is equal to val, then that element will not be assigned to num and not be included in the new list.


As I mentioned in previous article, nums[:] allows you to replace the original list nums with a new list.


So, when we return nums, the new list should be [2, 0, 5, 6, 4], which all val (3) are filtered out.








Give yourself a round of applause for finishing this tutorial!


Your dedication and commitment to learning are commendable.


See you in Python (4)!








© 2023 Harmony Pang. All rights reserved.


ความคิดเห็น


bottom of page