A Lesser-Known Difference Between For-Loops and List Comprehensions

Thinking from a scope perspective.

In the code above, the for-loop updated the existing variable (a), but list comprehension didn't. Can you guess why? Read more to know.

A loop variable is handled differently in for-loops and list comprehensions.

A for-loop leaks the loop variable into the surrounding scope. In other words, once the loop is over, you can still access the loop variable.

We can verify this below:

In the main snippet above, as the loop variable (a) already existed, it was overwritten in each iteration.

But a list comprehension does not work this way. Instead, the loop variable always remains local to the list comprehension. It is never leaked outside.

We can verify this below:

That is why the existing variable (a), which was also used inside the list comprehension, remained unchanged. The list comprehension defined the loop variable (a) local to its scope.

Over to you: What are some other differences that you know of between for-loops and list comprehension?

πŸ‘‰ Read what others are saying about this post on LinkedIn and Twitter.

πŸ‘‰ If you liked this post, don’t forget to leave a like ❀️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights. The button is located towards the bottom of this email.

πŸ‘‰ If you love reading this newsletter, feel free to share it with friends!

Hey there!

Thanks for being an avid reader and supporter of the Daily Dose of Data Science. I am beyond words to express how grateful I am that you make time every day to read this newsletter.

If you have been benefited from this newsletter in any way and my work makes your day just a little better by teaching you something new, then I would really appreciate it if you could write a review for Daily Dose of Data Science below:

Your contribution will immensely help me bring more readers to this newsletter. Thanks a lot for considering my request.

Your biggest fan,

Avi

Find the code for my tips here: GitHub.

I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn and Twitter.

Reply

or to participate.