python|June 03, 2019|2 min read

Python 3 - Magical Methods and Tricks with extremely useful methods

TL;DR

Explore handy Python tricks including exponentiation, list unpacking, dictionary merging, enumerate, zip, and other built-in methods for cleaner code.

Python 3 - Magical Methods and Tricks with extremely useful methods

This post will show some really awesome tricks in python.

Get the power of a number

Example, get 9^3 (9 to the power 3)

a ** b

5 ** 3
# 125

Get square root of a number

num ** 0.5

Tricks with print() method

print() method always put a new line character in the end. You can change that behavior as well

# ends with space
print(n, end=" ")

# ends with comma and a space
print(n, end=", ")

Count occurrence of words in a string

def count_words(line):
      result = {}
      words = line.split()
      for word in words:
          result[word] = result.get(word, 0) + 1

      return result

Or, a more better way to calculate count of words:

from collections import Counter
def count_words(line):
      return Counter(line.split())

Magic with Sequences

# Example array
a = [1, 2, 3, 4, 5]

# Get first element
a[0]

# Get last element
a[-1] 

# Get element from 1st to 4th index
a[1:5]

# Get last 5 elements
a[-5:]

# First five elements
a[:5]

# Skip first 5 elements
a[5:]

# Get from index: 2 to 7, but skip by 2 index
a[2:8:2]

# Reverse copy of a list
a[::-1]

# Get even indexes starting from 1
a[1::2]

Insert sub-array in between an array

a = [10, 20, 30, 40, 50]

# Insert [1, 2, 3, 4] after index=1
 a[1:1] = 1, 2, 3, 4
 print(a)
 [10, 1, 2, 3, 4, 20, 30, 40, 50]

Also, you can replace some indexes too

a = [10, 20, 30, 40, 50]

# Insert [1, 2, 3, 4] after index=2, and replace indexes=2,3
a[2:4] = 1, 2, 3, 4
print(a)
[10, 20, 1, 2, 3, 4, 50]

Replace sequence of indexes to a single number

a[2:7] = 778

i.e. replace indexes=2, 3, 4, 5, 6 and insert number 778

Insert in array at some position, and shift rest of array

Note: Above method replaces value at index specified. To just insert values, use below method

a = [10, 20, 30, 40, 50]
# Insert 90 at index=1
a.insert(1, 90)
print(a)
[10, 90, 20, 30, 40, 50]

Find an Odd number

No, I’m not showing n%2==0 kind of method

a = [1, 2, 3, 4, 5]
[ v for v in a if v & 1 ]

print(a)
[1, 3, 5]

Square of Odd numbers

a = [1, 2, 3, 4, 5]
[ v*v for v in a if v & 1 ]

print(a)
[1, 9, 25]

Capitalize all names which starts with letter ‘r’ (for example)

users = ["virat kohli", "ajay jadeja", "rohit sharma", "ram sharma"]

[ n.capitalize() for n in users if n[0] in 'rR']

['Rohit sharma', 'Ram sharma']

Create a dictionary of number and its square

a = [10, 20, 30]
{ v: v*v for v in a}
{10: 100, 20:400, 30:900}

Get a tuple of square

a = [10, 20, 30]

tuple(x*x for x in a)

(100, 400, 900)

Related Posts

How to Solve Circular Import Error in Python

How to Solve Circular Import Error in Python

Introduction To give some context, I have two python files. (Both in same folder…

Python 3 - Fun with Python String

Python 3 - Fun with Python String

This post some useful tips of using strings, and some issues while dealing with…

Python 3 - Format String fun

Python 3 - Format String fun

This post is dedicated for cases where we intend to append a variable value in a…

Understanding and Solving pylint errors for Python 3

Understanding and Solving pylint errors for Python 3

Pylint is an excellent tool to have good quality code. This post is not about…

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Introduction This post has the complete code to send email through smtp server…

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

Introduction It is very important to introduce few process so that your code and…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…