A few years back when I first started learning Python, I was kinda blown away by its succinctness and its expressiveness. Talking about myself, I had a background in C-style procedural languages, before I started learning Python.
One particular distinctive piece of syntax inside Python that I found particularly interesting was list comprehensions. Coming from a background in C-style programming languages, I had never seen a piece of syntax like it before and it kinda blew my mind. It is a way of iterating through a list and transforming each element of that list and compiling a new list having these transformed elements, in a single line of code! List comprehensions are not the only way of accomplishing this particular use case, we can possibly use a traditional for loop (though not in a single line) or we can also use a functional-style transformation function like ‘map’.
List comprehension has its counterparts for other types of Python data structures like for sets we have set comprehensions and for dictionaries, we have dictionary comprehensions.
List Comprehension Usage Examples
First, let’s see how iterating through an ordered sequence of elements works in a traditional procedural way. Say we have a list of numbers.