~/python/python-magical-methods-tricks.md

Python 3 - Magical Methods and Tricks with extremely useful methods

2 min readJune 03, 2019by Gorav Singal#python-3#python-tricks#python
// 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)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

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 Build Quality Gates with Pylint and Unittest Coverage Thresholds

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

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

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…