Python’s cool tricks for programming.

Aditya Dhanraj Tiwari
Analytics Vidhya
Published in
6 min readNov 7, 2020

--

Simplicity is Python’s way to solve a problem.

Created on memegenerator
  1. Reverse a string, list or tuple →

Whenever I’d find myself in a situation where I was required to perform a reverse operation, more often than not, I would use a for loop or resort to find some function like reverse() that had do the job for me.

But later on, to my shock I found, python has got another trick up it’s sleeve to solve this in a jiffy — Slicing Operation
You can use slicing [::-1] syntax to reverse a string, tuple or a list as well

string = 'John Wick'
print(string[::-1]) # logs: 'kciW nhoJ'
tup = (23, 45, 12, 56)
print(tup[::-1]) # logs: (56, 12, 45, 23)
l = ['john', 'baba', 'yaga', 'wick']
print(l[::-1]) # logs: ['wick', 'yaga', 'baba', 'john']

2. Check if given string is a palindrome →

Pretty easy, right? A lot of different approach comes to our mind when we think about this ways to solve this problem. But guess, one of the most simple way to solve this problem could again be the slicing operation.

Using the above discussed reversing trick, one line of code would be enough to check whether a given string is a palindrome or not. Firstly, we use string[::-1] to reverse the string and then we simply compare our original string with the reversed string string == string[::-1] to get the result.

string = 'aibohphobia'
print('Palindrome' if string == string[::-1] else 'No Plaindrome')
# print: Palindrome
string = 'johnwick'
print('Palindrome' if string == string[::-1] else 'No Plaindrome')
# print: No Plaindrome

3. Get “n” number of largest or smallest elements from a list →

Today, we will be using python’s standard library heapify to convert our list into heap and then use nlargest(n, iterable) and nsmallest(n, iterable) method to find “n” number of largest and smallest elements from our heap.

lis = [23, 9, 34, 22, 43, 21, 5, 40]import heapq
heapq.heapify(lis) # Convert list into min heap
print(heapq.nlargest(4, lis)) # will print 4 largest elements
# print: [43, 40, 34, 23]
print(heapq.nsmallest(4, lis)) # will print 4 smallest element
# print: [5, 9, 21, 22]

4. Swap 2 element without using a third variable →

This question would come up rather frequently to me in job interviews and the interviewer (if not from python background) would get irritated when I’d use this trick. But a python enthusiast/developer, you’d always find yourself be in better position when you know such tricks.

Simply use a,b = b,a to swap the values of both the variables. If you are interested to know how this internally works, refer this explanation.

a = 10
b = 25
print(f'a: {a}, b: {b}') # print: a: 10, b: 25
a,b = b,a # swapping variable
print(f'a: {a}, b: {b}') # print: a: 25, b: 10

In interviews, you can always resort to the old ways to answer →

a,b = 10, 25
a = a ^ b
b = a ^ b
a = a ^ b
print(f'a: {a}, b: {b}') # print: a: 25, b: 10

5. Count occurrence of each element in a string, tuple and list →

Python has an amazing collections module which contains many useful utilities. For our task, we are going to use Counter from collections module.

First, let’s split our string using split() function which returns us a list of strings split on spaces by default →

quoteFromGeeta = '''senses exists beyond body
mind exists beyond senses
intelligence exists beyond mind
and knowing yourself exists beyond intelligence'''
word_list = quoteFromGeeta.split()
print(word_list)
#print: ['senses', 'exists', 'beyond', 'body', 'mind', 'exists', 'beyond', 'senses', 'intelligence', 'exists', 'beyond', 'mind', 'and', 'knowing', 'yourself', 'exists', 'beyond', 'intelligence']

Now using Counter, Let’s find out the count of each word in our word_list →

from collections import Counterc = Counter(word_list) # pass your list to Counter[print(f'Word: {word}, Count: {count}') for word,count in c.items()]# prints
Word: senses, Count: 2
Word: exists, Count: 4
Word: beyond, Count: 4
Word: body, Count: 1
Word: mind, Count: 2
Word: intelligence, Count: 2
Word: and, Count: 1
Word: knowing, Count: 1
Word: yourself, Count: 1

Easy, isn’t it?

You can also find most common words using most_common(n) method

common_words = c.most_common(3)
[print(word, count) for word,count in common_words]
# print
Word: exists, Count: 4
Word: beyond, Count: 4
Word: senses, Count: 2

6. Check if two strings are Anagram →

You must be wondering, what is an Anagram, right ?
An anagram of a string is a string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other.

Using Counter from collections , we can easily check if two strings are anagram or not →

from collections import Counter
str1 = 'abcd'
str2 = 'dabc'
c1 = Counter(name1)
c2 = Counter(name2)
print(c1 == c2) # print True

7. Check for more than two conditions using Operator Chaining →

Checking a value for multiple conditions is a task we perform on daily basis, Let’s consider an example where we need to check for 5 < a < 20

In other programming languages, you would check it like this →

if a > 5 and a < 20:
pass

In python, you can simply use operator chaining →

if 5 < a < 20:
pass

8. Fetch values from list and assign to variables →

To solve this problem, we will use a concept that is still elusive to a lot of developers — Unpacking

Although most of us might have used it at some point but the concept in itself is something that would peek your interest. If you are new to this concept, then you are definitely going to learn something awesome today.

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. You will love the Unpacking feature in Python.

Time for an example →

l = ['john', '40', 'assassin']
#with out unpacking feature
name = l[0]
age = age[1]
profession = l[2]
#with unpacking feature
name, age, profession = l

To explore it’s working in depth, refer to this article from Stackabuse for an amazing explanation.

9. Get last element of list, string and tuple →

Let’s see a solution that will make it look like a piece of cake to solve this problem. Using iterable[-1] to find the last element.

l = ['john', '40', 'assassin']
print(l[-1]) # 'assassin'

10. Check if a list or tuple is empty

If you have always found it cumbersome to check if a list is empty or not. And if you have been using such tedious and messy approach like the one shown below, then we are going to witness something that will make our life so much easier. First, let us see the more conventionally used way →

temp = []
if len(temp) == 0:
pass
if len(temp):
pass

In python, an empty list is considered as a false so you can directly check it like the way shown below →

if temp:
pass

11. Concatenate two list, tuple →

You can use + operator to concatenate tuple and list, after performing concatenation it will return new tuple or list.

# On list
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
list_new = list1 + list2
print(list_new) # print [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# On tuple
tuple1 = (1,2,3,4,5)
tuple2 = (6,7,8,9,10)
tuple3 = (11,12,13,14,15)
tuple_new = tuple1 + tuple2 + tuple3
print(tuple_new)

12. Create a new list from existing list →

Let’s understand our problem statement with an example.

l = ['John Wick', 45, 'assassin']new_l =  l # this will copy the reference of l in new_lprint(new_l) # print  ['John Wick', 45, 'assassin']l[0] = 'Baba Yaga' # any change in l will reflect to new_l alsoprint(new_l) # print ['Baba Yaga', 45, 'assassin']

From above snapshot, it is evident that the new list variable just stored a reference address of the existing list and now points to it but as per our requirement a new list was not created.

To create a totally new list, you can simply use list[:] on the existing list and you will have a new list through one simple operation.

l = ['John Wick', 45, 'assassin']new_l =  l[:] # this will create the new listprint(new_l) # print  ['John Wick', 45, 'assassin']l[0] = 'Baba Yaga' # any change in l will reflect to new_l alsoprint(new_l) # print ['John Wick', 45, 'assassin']

Note: list[:] will create a shallow copy of list, to make a deep copy you can use deepcopy method from copy module

To be Continued…

There are more cool libraries in python like functools, itertools, pandas which we will explore in further articles.

Hope you have enjoyed the article. Please do tell me in comment, which trick you like most.

Good Luck, Happy Coding 😃

--

--