List Comprehension

List comprehension is a way of making new lists. It allows you to create a list from any iterable object in a concise and efficient manner. See the basic syntax below:

# list comprehension syntax
new_list = [x for x in some_iterable]

Here you can see that list comprehension is specified by square brackets (just like the list itself) inside which you have a for loop over some iterable object. In our example, new_list will simply consist of all elements from some_iterable object. The code above is completely equivalent to the one below, however, it takes less space and works a little bit faster!

# the equivalent code
new_list = []
for x in some_iterable:
    new_list.append(x)

list comprehensions are used not just for copying elements from some iterable into a list, but mainly for modifying them in some way to create a specific new list. In this case, in the first place of the list comprehension, we write some function of our variable. For example, the code below shows how to create a list of squared numbers.

# squared numbers
numbers = [1, 2, 3]
square_list = [x * x for x in numbers]  # [1, 4, 9]

Also, we can use list comprehensions to convert elements of a list from one data type to another:

# from string to float
strings = ["8.9", "6.0", "8.1", "7.5"]
floats = [float(num) for num in strings]  # [8.9, 6.0, 8.1, 7.5]

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s