Your Voice, Our Headlines

Download Folkspaper App with no Ads!


A fast-growing newspaper curated by the online community.

The Best Programmers Use These 5 Slick Python Tricks

  • tag_facesReaction
  • Tip Bones

Python is one of the most preferred languages when it comes to programer proclivity. Its brevity, high-readability, and versatility have enabled Python’s use over an extensive range of applications across various domains. But, as even the most practised programmers will acknowledge, mastering Python and curating a beautiful and vernacular code is not everyone’s cup of tea. The best and the most powerful Pythonic codes are those that stem from ingenious, yet simple tips and tricks. The snippets refine the code’s logic, make it more manageable and robust, and allow efficient and smooth execution of the main program.  

Here are a few Python gems that will up your programming game.

1. Swap: In place swapping of 2 numbers

The programming principle of equality eliminates the ordeal of using a temporary variable. The following trick allows value to be mutually exchanged meanwhile minimizing the runtime.   

x, y = 10, 20 

print(x, y)

x, y = y, x

print(x, y)


10 20

20 10

2. Single list: Get your data in one line

This hack elides excessive labour, calling modules to implement a number of iteration building blocks for efficient looping.

a = [[1, 2], [3, 4], [5, 6]] 

import itertools


[1, 2, 3, 4, 5, 6]

3. Return: Function that outputs multiple values 

In Python, we can return multiple values from a function in numerous ways; these may involve using an object, list, tuple or a dictionary. The following bit illustrates the simplest method to return multiple values.

def x():  

 return 1, 2, 3, 4

a, b, c, d = x()

print(a, b, c, d)

4. Search: Find the most frequent value in a list

Python enables analysts and programmers to perform some statistical evaluation on a series of input data. To find the mode,i.e. The most frequently occurring value in the list, use this straightforward strategy.

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]  

print(max(set(test), key = test.count))

5. Anagram checker: Determine if two words are anagrams. 

Given two strings, s1 and s2, this uncomplicated Pyhtonic tip will verify if the two strings are anagrams of one another. An anagram of a string is another string that contains the same characters, only the order of characters can be different.

def is_anagram(word1, word2): 

    word1: string

    word2: string

    returns: boolean