4 Life-Changing Python Tricks To Write Less Code

Liu Zuo Lin
CodeX
Published in
4 min readSep 3, 2021

--

Tired of typing too much code in Python? Ready for some transformational changes you can apply to shorten your code? Jokes aside, here are 4 Python tips I’ve picked up over the years that has enabled me to write the same functionality while typing less.

Iterating Through Multiple Lists At Once with Zip

fruits = ["apple", "orange", "pear"]
quantities = [2,4,6]

Let’s say we have 2 lists — fruits that contain a bunch of fruits, and quantities that contains numbers representing how many of each fruit there is. We now want to print out how many of each fruit is available. This is how we might do it:

for i in range(len(fruits)):
fruit = fruits[i]
qty = quantities[i]
print(fruit, qty)

Or this if we want to do it in even fewer lines:

for i in range(len(fruits)):
print(fruits[i], quantities[i])

However, we need to deal with indexes here, which can be annoying and a potential breeding ground for bugs.

The zip function

With the zip function, we can do this without needing to care about the index. The zip function essentially allows us to iterate through 2 (or more) lists at once, like this:

--

--