A common refrain you hear is that list comprehension is quicker than using for loops to process your data. This will be the first part in a multi-part series looking into the how and why. Most python coders I’ve interacted with don’t even consider how to use a list comprehension or even know what it is. Many don’t
A great way to experiment with this concept is using large datasets. Gapminder is a great way to explore features using a large data set.
https://github.com/jennybc/gapminder -> gapminder/data-raw/xls/gapdata003.xls
I grab the data and import it using pandas(just because it’s super easy). I take the values in one column put them into a list and use a dictionary for the data set. This allows me to loop through the data and do a dirty comparison. This isn’t work to solve a problem here but is a common data style I’ve run into maintaining large networks.
GAP data inside of a Dataframe ->

Setting up the Data structures ->
country = gap_df["Area"].values.tolist()
country_set = set(country)
gap_dict = gap_df.to_dict()
Code language: Python (python)
country_set is set up as a set to remove duplicate values. Often a common list from a single source to compare against items like logs with multiple entries per item. gap_dict is to mimic a complex data structure where you have to iterate over many entries to arrive at a solution.
Now let’s compare the speed of a nested for loop inside and outside of a list comprehension. I’m using %%time as this a magic variable to help you determine the time it takes to run a cell in jupyter.
%%time
fast_list = [country for country in country_set for k,v in gap_dict["Area"].items() if country in v]
len(fast_list)
Code language: JavaScript (javascript)
Results:
CPU times: user 127 ms, sys: 941 μs, total: 128 ms
Wall time: 127 ms
21515
Let’s compare to a common for structure loop I find in many peoples code.
%%time
new_slow_list = list()
for k,v in gap_dict["Area"].items():
for country in country_set:
if country in v:
new_slow_list.append(country)
len(new_slow_list)
Code language: PHP (php)
Results for the slower list:
CPU times: user 217 ms, sys: 1.79 ms, total: 219 ms
Wall time: 218 ms
21515
Code language: CSS (css)
The results are pretty staggering.
For loop: 217ms
List comp: 127ms
The list comprehension cuts the processing time nearly in half. Next steps of exploring this tool is why does a list comprehension speed up the results?
