List Comprehension in Python
I stumbled across this nice tutorial on advanced design patterns in python today, and especially liked the following image that explains graphically what list comprehension is:
List comprehension in python is extremely flexible and powerful. Let us practice some more with further neat examples of it:
Square all non-negative numbers smaller than 10
[x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Non-negative multiples of 5 smaller than 100
[x for x in range(100) if x%5 == 0]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
Non-negative multiples of 3 but not multiples of 6 smaller than 50
[x for x in range(50) if x%3 == 0 and x%6 != 0]
[3, 9, 15, 21, 27, 33, 39, 45]
All consonants in a given sentence (without repetition)
import string punct = string.punctuation + ' ' vowels = "aeiou" phrase = "On second thought, let's not go to Camelot. It is a silly place." set([c for c in phrase.lower() if c not in vowels and c not in punct])
{'c', 'd', 'g', 'h', 'l', 'm', 'n', 'p', 's', 't', 'y'}
First character of every word in a sentence
[w[0] for w in phrase.split()]
['O', 's', 't', 'l', 'n', 'g', 't', 'C', 'I', 'i', 'a', 's', 'p']
Substitute all vowels in a sentence by the character ‘0’
"".join([c if c not in vowels else '0' for c in phrase])
"On s0c0nd th00ght, l0t's n0t g0 t0 C0m0l0t. It 0s 0 s0lly pl0c0."
Pairs of elements drawn from different lists
words1 = ['Lancelot', 'Robin', 'Galahad'] words2 = ['Camelot', 'Assyria'] [(w1,w2) for w1 in words1 for w2 in words2]
[('Lancelot', 'Camelot'), ('Lancelot', 'Assyria'), ('Robin', 'Camelot'), ('Robin', 'Assyria'), ('Galahad', 'Camelot'), ('Galahad', 'Assyria')]
I will update this list as more interesting and useful examples come to mind. What’s your favorite use of list comprehension and how many lines of code did it save you?
The last example (which is a Cartesian Product) has a higher order function called “product” in itertools. http://docs.python.org/2/library/itertools.html#itertools.product
In fact, if you look at the description of the function it does the very same list comprehension to give the Cartesian Product.
Indeed itertools rocks, and I love product, permutation, combination, etc. It is also more efficient than my example since it uses generators (just imagine if words1, words2 where *huge* lists, list comprehension wouldn’t be very good then).
So yeah, hurra for itertools; my example was just to show that one can loop over two or more entities using list comprehension.
This is great. One the best write ups on list comprehensions I have ever seen
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
https://www.besanttechnologies.com/training-courses/python-training-institute-in-bangalore
Thanks for sharing such a wonderful information, keep going on. I really enjoyed it.
http://www.softlogicsys.in/python-training-in-chennai
Data for a Data Scientist is what Oxygen is to Human Beings. data analytics courses This is also a profession where statistical adroit works on data – incepting from Data Collection to Data Cleansing to Data Mining to Statistical Analysis and right through Forecasting, Predictive Modeling and finally Data Optimization.
Hey, thanks for this great article I really like this post and I love your blog and also Check marketing analytics certification in hyderabad at 360DIGITMG.
360Digitmg marketing analytics in hyderabad
Awesome. I read this post so nice and very informative information…thanks for sharing data science course in Chennai 360 digital
data science course
Data science course chennai
I appreciate the practical examples provided in this article, as they illustrate the application of data science concepts effectively.
data science course in nagpur
The real-world case studies included in this article make it relatable and demonstrate the practical application of data science.
Data Science course In Faridabad
Great post! Thank you for sharing this informative post. It was a pleasure to read and contributed to enhancing my knowledge with the latest information. Keep blogging!
python course in Bangalore
python classes in bangalore
python coaching in bangalore
python programming classes in bangalore
I appreciate the inclusion of best practices for data cleaning and preprocessing in this article…… data science course in chennai with placement