Everything You Need To Know About Python Comprehensions For List, Set And Dictionary

Photo by Karsten Würth on Unsplash
Photo by Karsten Würth on Unsplash
Photo by Karsten Würth on Unsplash

Introduction

Python comprehension basic syntax

List comprehension

words = [ 
"Serendipity",
"Petrichor",
"Supine",
"Solitude",
"Aurora",
"Idyllic",
"Clinomania",
"Pluviophile",
"Euphoria",
"Sequoia"]
short_words = [word for word in words if len(word) < 8 ]
['Supine', 'Aurora', 'Idyllic', 'Sequoia']
short_s_words = [word for word in words if len(word) < 8 if word.startswith("S") ] #short_s_words = [word for word in words if len(word) < 8 and word.startswith("S") ]
short_or_s_words = [word for word in words if len(word) < 8 or word.startswith("S") ]
['Serendipity', 'Supine', 'Solitude', 'Aurora', 'Idyllic', 'Sequoia']
lat_long = [[1.291173,103.810535], [1.285387,103.846082], [1.285803,103.845392]] [x for pos in lat_long for x in pos]
[1.291173, 103.810535, 1.285387, 103.846082, 1.285803, 103.845392]
[(word, num) for word in words if word.startswith("S") for num in range(4) if num%2 == 0]
[('Serendipity', 0), 
('Serendipity', 2),
('Supine', 0),
('Supine', 2),
('Solitude', 0),
('Solitude', 2),
('Sequoia', 0),
('Sequoia', 2)]
[(word, num) for word, num in zip(words, range(len(words))) if word.startswith("S") and num%2 == 0]
import os 
[os.path.join(dir[0], file) for dir in os.walk(".") if not ".ipynb_checkpoints" in dir[0] for file in dir[2] if file.endswith(".ipynb")]
[(word, len(word)) for word in words]

Set comprehension

words_set = set(words) 
short_words_set ={word for word in words_set if len(word) < 8}
{'Aurora', 'Idyllic', 'Sequoia', 'Supine'}
short_words_set = {word for word in words if len(word) < 8}

Dictionary comprehension

dict_words = {word: len(word) for word in words}
{'Serendipity': 11, 
'Petrichor': 9,
'Supine': 6,
'Solitude': 8,
'Aurora': 6,
'Idyllic': 7,
'Clinomania': 10,
'Pluviophile': 11,
'Euphoria': 8,
'Sequoia': 7}
s_words_dict = {word: length for word, length in dict_words.items() if word.startswith("S")}
{'Serendipity': 11, 
'Supine': 6,
'Solitude': 8,
'Sequoia': 7}

Limitations and constraints

list(map(lambda x: x, filter(lambda word: len(word) < 8, words)))
w_generator = ((word, length) for word, length in dict_words.items() if word.startswith("S"))
for x in w_generator: 
print(x)
('Serendipity', 11) 
('Supine', 6)
('Solitude', 8)
('Sequoia', 7)

Conclusion

Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store