# Python 3 - Magical Methods and Tricks with extremely useful methods

June 03, 2019

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

## Similar Posts

### Resolving Checkmarx issues reported

So, here we are using input variable String[] args without any validation…

### Drupal 8 - How to Theme Form and its Fields with reordering fields

Introduction In this post, we will see how to theme form and its fields…

### How to create Repository using Github Rest API, Configure Visibility and Assign a Team as Readonly

Introduction I had to create many repositories in an Github organization. I…

### Kubernetes - How to Configure Docker Repository to Pull Image and Configure Secret

Introduction In most of cases, you are not pulling images from docker hub public…

### Drupal 8 - How to hide help link About text formats and text format guidelines

Problem In drupal textarea field, it was always a pain to see the two links…

## Latest Posts

### Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Introduction In this post we will see following: How to schedule a job on cron…

### How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

Introduction There are some cases, where I need another git repository while…

### How to Fetch Multiple Credentials and Expose them in Environment using Jenkinsfile pipeline

Introduction In this post, we will see how to fetch multiple credentials and…

### Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Introduction I have an automation script, that I want to run on different…

### Jenkinsfile - How to Create UI Form Text fields, Drop-down and Run for Different Conditions

Introduction I had to write a CICD system for one of our project. I had to…

### Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Introduction Java log4j has many ways to initialize and append the desired…