python2 Min Read

Python 3 - Magical Methods and Tricks with extremely useful methods

Gorav Singal

June 03, 2019

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)
Share

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

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI video generation went from “cool demo” to “usable in production” in 2024-202…

AI Models in 2025 — Cost, Capabilities, and Which One to Use

AI Models in 2025 — Cost, Capabilities, and Which One to Use

Choosing the right AI model is one of the most impactful decisions you’ll make…

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

Generating one image with AI costs between $0.002 and $0.12. That might sound…

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

Two years ago, AI coding meant one thing: GitHub Copilot autocompleting your…

AI Agents Demystified — It's Just Automation With a Better Brain

AI Agents Demystified — It's Just Automation With a Better Brain

Let’s cut through the noise. If you read Twitter or LinkedIn, you’d think “AI…

Supply Chain Security — Protecting Your Software Pipeline

Supply Chain Security — Protecting Your Software Pipeline

In 2024, a single malicious contributor nearly compromised every Linux system on…