List Comprehension

Huda
4 min readOct 21, 2021
Photo by <a href=”https://unsplash.com/@tine999?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Tine Ivanič</a> on <a href=”https://unsplash.com/s/photos/loop?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Photo by Tine Ivanič on Unsplash

Loops are one of the best code compressors when it comes to programming languages. Implementing loops is an efficient way of asking the computer to run the same set of commands multiple times. Each iteration of the loop can use new data to perform the command or use the data obtained from the previous run. Thus, a loop can help reduce redundancy within the code.

There are two main types of loops for and while. Both of these loops are common across all popular languages. We’ll be focusing on the for loop for the scope of this blog.

Normal For Loop

We can use for loop when the number of iterations required is known. For example, suppose we have to copy every element of a list of 10 elements into a new list, then we can use the for loop as:

Here, initially, we define a new empty list. Then, we iterate over every element of the numbers list and append that element to the new_list. Thus, we implement the above logic with some long and extensive syntax. However, what if we could implement the same logic with just one line of code? Enter List Comprehension.

List Comprehension

--

--

Huda

Data Scientist with recent experience in data acquisition and data modeling, statistical analysis, machine learning, deep learning and NLP