Python 3.0 learnings – List comprehensions

One of the strengths of a simple (yet powerful) language like Python is to achieve the same with less lines of code.

A “Pythonic” concept that proves this is list comprehensions

Simply put, it enables you concisely create a list in a single line of code based on some logic presented as an iterable object

Syntax is –

<to_be_create_list_name> = [i for i in <logic to create an iterable object(s)>]

And they powerful thing is that conditionals can be used in the above syntax of create an iterable object based on some conditional logic

Example –

You are given a list that has blank space characters in it, find out at which positions in the list do those blank space chars exist ? and create a new list with to hold those positions ( to be used downstream for a business rule)

Solution # 1 –

My original bloatey way to achieve it was

Solution # 2 –

A much more concise way discovered (through googling) that uses list comprehension  😉

Note – how the condition to check for blank chars and the loop to iterate through the link of the list, have been combined into a single line

Python 3.0, you beauty !




Leave a Reply