Python Tricks To Reduce Lines Of Code

Sakina Fakhruddin
Women Data Greenhorns
4 min readJul 31, 2018
Python: Logo From: Wikimedia Commons, the free media repository

Let’s face it! Even if you have been programming for a few months, there was a point when you went back to your old code and scratched your head wondering what you have written. It has happened to the best of us. I have recently been learning python, a language that has gotten popular for its readability and easy-to-write syntax. I had to, once again, scour the internet in search of some good ways to write python code making it clean and efficient and here are some of the best tips I found :

Iterating List

Ah! This has to be the perfect place to start from: Lists. In Java if you need to iterate lists, you have to do

//For single listsfor(int i=0, i < list.length(), i++){
//your code here
}
//For iterating 2 listsfor(int i=0, i < max(lista.length(),listb.length()), i++){
//your code here
}

In python, you can of course write the same code without the brackets and correct indentation but there’s an easier and more pythonic way of writing this code.

#for single listsfor element in list:
#your code here.
#for two listsfor elementA,elementB in zip(listA, listB):
#your code here

And that’s it. So easy and concise.

Swapping Variables

Let me show you the bad way:

a = 2
b = 4
temp = a
a = b
b = temp

Again, there’s a single liner for doing this the Pythonic way:

a = 2
b = 4
a,b = b,a

Python does it all for you. Now that’s what I call easy to write code!

Reversing an Object

I’ll be very honest with you; I found this trick while doing a HackerRank challenge where the task is to reverse a string. In python, there are two very easy ways to reverse an object and both are single lined.

string = “String to reverse”#The first way
print(reversed(string))
#The second way
print(string[::-1])

For those who do not get the second technique, you are printing a string from the last element and moving backwards without stepping over any letter.

Boolean If Conditions

So, let’s suppose you have to find whether an element ‘a’ exist in a list with more than one element. Normally, you’d write an if condition to check if present then do something but if not then do something else more like:

ilist = [‘a’,’b’,’c’,’d’,’e’,’f’]if ‘a’ in ilist:
print(‘Yes! Found a.’)
else:
print(‘Not found’)

This is not the Pythonic way. In python, of course, this is a single line

print(‘Yes! Found a’ if a in ilist else ‘Not found’)

Check Key in Dictionary

Continuing with single line checks if you want to check a key in a dictionary, similar to the scenario above, here’s the python equivalent of it:

idict = {a : 1,
b : 2,
c : 3,
d : 4,
e : 5,
f : 6}
ival = idict.get(‘a’,’Not Found’)

This line of code will fill your variable with the value of a if found. If not found, then the variable will be filled with Not Found.

Reading From Files

If you are coming from another language like me, you will probably do this the bad way i.e

f = open(‘somefile.txt’)
text = f.read()
for line in text.split(‘/n’):
print(line)
f.close()

But the Pythonic way to do this is:

with open(“somefile.txt”) as f:
text = f.readlines()

Separating List Elements

I found this after an extensive search as I had a function where I wanted to separate the first and the last element from the list and return the middle portion back. This resulted in a lengthy code where I would loop over the list and copy everything from the second element to the second-last element to a new list. However, leave it to the python creators to come up with something so simple, it makes you happy.

Here’s how you can separate the first element, the last element and the rest of the list in one single line of code.

ilist= [1,2,3,4,5,6,7]first, *rest, last = ilist

This can be used to extract however many elements you want. Suppose you want to select the whole list: *ilst is what you use.

Tuple Comparison

In all honesty, once again, I found this on HackerRank when I was stuck on a challenge and I was so impressed with python’s capabilities that I had to put this on this list. Suppose you want to check three variables together, how would you go about it? In a single line of code, of course!

var_1, var_2, var_3 = 1, 3, 4
var_4, var_5, var_6 = 7, 8, 55
#Now the comparisons
if (var_1, var_2, var_3) <= (var_4, var_5, var_6):
#do something
elif (var_2, var_3) == (var_5, var_6):
#do some other thing
elif var_3 == var_6:
#do a third thing
else:
#finally do this

Yes! It is literally that easy.

These eight techniques are used in the writing good code daily and for me I have been using them quite a bit since I have discovered them. It makes my life easier. Here’s to hoping they make your life easier as well. Cheers!

--

--