Quick Introduction List Comprehension in Python

List comprehension creates a new list. Inside the list comprehension, each iteration creates a tuple containing the current key and value.

The following example will only return even numbers from a list passed into the function


def filter_even_numbers(numbers):

    """Returns a list of only even numbers"""

    even_numbers = [num for num in numbers if num % 2 == 0]

    return even_numbers


if __name__ == '__main__':

    numbers=[1, 2, 3, 4, 5, 6]

    even_list = filter_even_numbers(numbers)

    print(numbers)

    print(even_list)


For example, when you run the code, you will get the following results for the input:


$ python3 example2.py

[1, 2, 3, 4, 5, 6]

[2, 4, 6]


Looking to expand your Python knowledge? I recommend checking out the book "Mastering Learning Python 3: In Five Minutes." This resource offers a beginner-friendly approach with short, focused lessons that can help you grasp the fundamentals of Python 3 programming. (*** Now available on Amazon ***)