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


list_2 = [] #create a blank to be populated list
for x in range(len(list_1)): # loop through the lenght of the original list
if list_1[x] == ' ': # if the value at that particular index is a blank space
list_2.append(x) # add the index to the new list
print(list_2)

Solution # 2 –

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


list_2 = [x for x in range(len(list_1)) if list_1[x] == ' ']

view raw

List_comp.py

hosted with ❤ by GitHub

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s