Member-only story

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

codeforests
5 min readNov 1, 2020

--

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

Introduction

Python comprehension is a set of looping and filtering instructions for evaluating expressions and producing sequence output. It is commonly used to construct list, set or dictionary objects which are known as list comprehension, set comprehension and dictionary comprehension. Comparing to use map or filter or nested loops to generate the same result, comprehension has more concise syntax and improved readability. In this article, I will be explaining these three types of comprehensions with some practical examples.

Python comprehension basic syntax

You may have seen people using list/set/dict comprehension in their code, but if you have not yet checked the Python documentation, below is the syntax for Python comprehension.

Assignment Expression for target in iterable [if condition]

It requires a single assignment expression with at least one for statement, and following by zero or more for or if statements.

With this basic understanding, let’s dive into the examples.

List comprehension

List comprehension uses for and if statements to construct a list literal. The new…

--

--

codeforests
codeforests

Written by codeforests

Resources and tutorials for python, data science and automation solutions

No responses yet