x for x in Python

Introduction

This is going to be a compact post. Did the title catch your attention? Actually, It was intentional as we could have named it list comprehensions in Python. Looping in Python is awesome, if you are curious, you may check this post for more details about loops. In this post, we are only going to talk about list comprehensions, giving few examples and cutting on the details.

Let us start…

List Comprehensions

List comprehensions in Python is a fancy programming style to create a list. It is a powerful technique and makes the code looks neat. Let us take few examples to demonstrate that…

Example 1

We are going to generate the even numbers between 0 and 10 using a for loop…

Doing the same using a list comprehension…

Example 2

In this example, we are going to convert all elements in a two dimensional array to numbers using a nested loop…

If you run the code snippet above, you should get the following output…

Doing the same using a list comprehension…

As you can see, list comprehensions syntax is quite simple:

Hopefully you got an idea what list comprehension means in Python.

That is it for today. Thanks for visiting. For feedback, please use the comments section below.

Tags:

Add a Comment

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