the reluctant tester

Perpetual learner of the craft of Software Testing,Servant Leadership and creating better Teams

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

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

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: Logo

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

Facebook photo

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

Connecting to %s

About Me

I’m Sunjeet Khokhar

An experienced People Leader,Practice Lead  and Test Manager .

I am driven by the success of people around me, am a keen student of organisational behaviour and firmly believe that we can be better craftspeople by being better humans first.

CoNNECT with Me

%d bloggers like this: