Member-only story
4 Ways To Shorten Your Python Code Like A Pro
One reason why so many programmers are a fan of Python is probably because of how concise it is. When we want to print "hello world"
, we tell Python to print "hello world"
instead of defining a class, public static void main
method and all that stuff. In this article, let’s take a look at a couple of ways to shorten your Python code even further
1) List Comprehension
Let’s say we have a list [1,2,3]
and we wish to create another list with each number multiplied by 2 [2,4,6]
.
The Normal Way
lis = [1,2,3]
output = []
for number in lis:
output.append(number * 2)# output will be [2,4,6]
If we do this the normal way, we usually create an empty list to start with output
. We then iterate through lis
, and append number * 2
to output
, and we end up with output
being [2,4,6]
.
Using List Comprehension
If we use list comprehension, we can do this in 1 line instead of 3
lis = [1,2,3]
output = [number * 2 for number in lis]# output will be [2,4,6]
How This Works
lis = [1,2,3]
lis2 = [number for number in lis]