Member-only story

A Comprehensive Guide to List Comprehension in Python

Liu Zuo Lin
3 min readSep 8, 2021

--

If you’re somewhat comfortable with the basics of Python — data types, strings, lists, dictionaries and all that fun stuff, here’s one trick to take your code to another level — list comprehension. By another level, I mean that your code becomes 1–2 lines shorter and looks cooler :)

List Comprehension in a Nutshell

Let’s say we have a list of numbers of type string.

numbers = ["5", "6,", "7"]

We want to convert this list of strings into a list of integers

numbers2 = [5, 6, 7] # this is what we want

Solving this normally with Python basics

numbers = ["5", "6", "7"]
numbers2 = []
for num in numbers:
numbers2.append(int(num))
# numbers2 will be [5,6,7]

Solving this with List Comprehension in 1 line

numbers2 = [int(num) for num in numbers]# numbers2 will also be [5, 6, 7] + we save 1 line of code

List Comprehension Syntax

Essentially, list comprehension allows us to 1) create a copy of another list (or iterable) and 2) modify its values in one line. Given…

--

--

Liu Zuo Lin
Liu Zuo Lin

Written by Liu Zuo Lin

SWE @ Meta | [Ebook] 101 Things I Never Knew About Python: https://payhip.com/b/vywcf

No responses yet