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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 😉
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
list_2 = [x for x in range(len(list_1)) if list_1[x] == ' '] |
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