1
Spaces separate multiple inputs
This code lets you make multiple space-separated entries at once, and can come in handy whenever you're trying to solve a programming competition problem.
## Taking Two Integers as input
a,b = map(int,input().split())
print("a:",a)
print("b:",b)
## Taking a List as input
arr = list(map(int,input().split()))
print("Input List:",arr)
2
Simultaneous access to Index index and value
The enumerate() built-in function allows you to find both the index and the value in an or loop.
arr = [2,4,6,3,8,10]
for index,value in enumerate(arr):
print(f"At Index {index} The Value Is -> {value}")
'''Output
At Index 0 The Value Is -> 2
At Index 1 The Value Is -> 4
At Index 2 The Value Is -> 6
At Index 3 The Value Is -> 3
At Index 4 The Value Is -> 8
At Index 5 The Value Is -> 10
'''
3
Check memory usage
This code can be used to check the memory usage of an object.
4
Output the unique ID of a variable
The id() function allows you to find the unique id of a variable, you just need to pass the variable name in this method.
5
Check Anagram
An anagram means, by rearranging the letters of a word, using each original letter exactly once, to form another new word.
def check_anagram(first_word, second_word):
return sorted(first_word) == sorted(second_word)
print(check_anagram("silent", "listen")) # True
print(check_anagram("ginger", "danger")) # False
6
merge two dictionaries
This code is handy when you are working with databases and JSON files and need to combine multiple data from different files or tables into the same file. There are some risks in merging two dictionaries, such as what if there are duplicate keys? Fortunately, we also have a solution for this situation.
basic_information = {"name":['karl','Lary'],"mobile":["0134567894","0123456789"]}
academic_information = {"grade":["A","B"]}
details = dict() ## Combines Dict
## Dictionary Comprehension Method
details = {key: value for data in (basic_information, academic_information) for key,value in data.items()}
print(details)
## Dictionary unpacking
details = {**basic_information ,**academic_information}
print(details)
## Copy and Update Method
details = basic_information.copy()
details.update(academic_information)
print(details)
7
Check if a file exists
We want to make sure that the files used in the code still exist. Python makes managing files easy because Python has a built-in syntax for reading and writing files.
# Brute force Method
import os.path
from os import path
def check_for_file():
print("File exists: ",path.exists("data.txt"))
if __name__=="__main__":
check_for_file()
'''
File exists: False
'''
8
Square all numbers in a given range
In this code, we utilize the built-in function itertools to find the square of each integer in the given range.
# METHOD 1
from itertools import repeat
n = 5
squares = list(map(pow, range(1, n+1), repeat(2)))
print(squares)
# METHOD 2
n = 6
squares = [i**2 for i in range(1,n+1)]
print(squares)
"""Output
[1, 4, 9, 16, 25]
"""
9
Convert two lists to dictionary
The following method converts two lists into dictionaries.
list1 = ['karl','lary','keera']
list2 = [28934,28935,28936]
# Method 1: zip()
dictt0 = dict(zip(list1,list2))
# Method 2: dictionary comprehension
dictt1 = {key:value for key,value in zip(list1,list2)}
# Method 3: Using a For Loop (Not Recommended)
tuples = zip(list1, list2)
dictt2 = {}
for key, value in tuples:
if key in dictt2:
pass
else:
dictt2[key] = value
print(dictt0, dictt1, dictt2, sep = "\n")
10
Sort a list of strings
This code can be very useful when you get a list of student names and want to sort all names.
list1 = ["Karl","Larry","Ana","Zack"]
# Method 1: sort()
list1.sort()
# Method 2: sorted()
sorted_list = sorted(list1)
# Method 3: Brute Force Method
size = len(list1)
for i in range(size):
for j in range(size):
if list1[i] < list1[j]:
temp = list1[i]
list1[i] = list1[j]
list1[j] = temp
print(list1)
11
Understanding Lists with if and Else
This code is useful when you want to filter a data structure based on some criteria.
12
Add elements from two lists
Suppose you have two lists and want to combine them into one list by adding their elements, this code would be useful in this scenario.
maths = [59, 64, 75, 86]
physics = [78, 98, 56, 56]
# Brute Force Method
list1 = [
maths[0]+physics[0],
maths[1]+physics[1],
maths[2]+physics[2],
maths[3]+physics[3]
]
# List Comprehension
list1 = [x + y for x,y in zip(maths,physics)]
# Using Maps
import operator
all_devices = list(map(operator.add, maths, physics))
# Using Numpy Library
import numpy as np
list1 = np.add(maths,physics)
'''Output
[137 162 131 142]
'''
13
Sort dictionary list
When you have a list of dictionaries, you may want to put them in order with the help of keys.
dict1 = [
{"Name":"Karl",
"Age":25},
{"Name":"Lary",
"Age":39},
{"Name":"Nina",
"Age":35}
]
## Using sort()
dict1.sort(key=lambda item: item.get("Age"))
# List sorting using itemgetter
from operator import itemgetter
f = itemgetter('Name')
dict1.sort(key=f)
# Iterable sorted function
dict1 = sorted(dict1, key=lambda item: item.get("Age"))
'''Output
[{'Age': 25, 'Name': 'Karl'},
{'Age': 35, 'Name': 'Nina'},
{'Age': 39, 'Name': 'Lary'}]
'''
14
Calculate the time of the shell
Sometimes it is important to know the execution time of a shell or a piece of code so that a better algorithm can be achieved with the least amount of time.
# METHOD 1
import datetime
start = datetime.datetime.now()
"""
CODE
"""
print(datetime.datetime.now()-start)
# METHOD 2
import time
start_time = time.time()
main()
print(f"Total Time To Execute The Code is {(time.time() - start_time)}" )
# METHOD 3
import timeit
code = '''
## Code snippet whose execution time is to be measured
[2,6,3,6,7,1,5,72,1].sort()
'''
print(timeit.timeit(stmy = code,number = 1000))
15
Check for substrings in a string
One of the things I encounter every day is to check if a string contains a certain substring. Unlike other programming languages, python provides a nice keyword for this.
addresses = [
"12/45 Elm street",
'34/56 Clark street',
'56,77 maple street',
'17/45 Elm street'
]
street = 'Elm street'
for i in addresses:
if street in i:
print(i)
'''output
12/45 Elm street
17/45 Elm street
'''
16
string format
The most important parts of the code are the inputs, logic and outputs. During programming, all three parts require a certain format for better, easier-to-read output. Python provides several ways to change the format of strings.
name = "Abhay"
age = 21
## METHOD 1: Concatenation
print("My name is "+name+", and I am "+str(age)+ " years old.")
## METHOD 2: F-strings (Python 3+)
print(f"My name is {name}, and I am {age} years old")
## METHOD 3: Join
print(''.join(["My name is ", name, ", and I am ", str(age), " years old"]))
## METHOD 4: modulus operator
print("My name is %s, and I am %d years old." % (name, age))
## METHOD 5: format(Python 2 and 3)
print("My name is {}, and I am {} years old".format(name, age))
17
error handling
Like Java and C++, python also provides try, except and finally methods to handle exception errors.
# Example 1
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print(c)
except:
print("Can't divide with zero")
# Example 2
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
# Example 3
try:
fptr = open("data.txt",'r')
try:
fptr.write("Hello World!")
finally:
fptr.close()
print("File Closed")
except:
print("Error")
18
The most common element in a list
The following method returns the most frequently occurring element in the list.
19
Evaluate without if - else
This code shows how to simply write a calculator without using any if-else conditions.
import operator
action = {
"+" : operator.add,
"-" : operator.sub,
"/" : operator.truediv,
"*" : operator.mul,
"**" : pow
}
print(action['*'](5, 5)) # 25
20
Chained Function call
In python, you can call multiple functions on the same line of code.
def add(a,b):
return a+b
def sub(a,b):
return a-b
a,b = 9,6
print((sub if a > b else add)(a, b))
21
exchange value
Here's a quick way to swap two numeric values without needing another extra variable.
a,b = 5,7
# Method 1
b,a = a,b
# Method 2
def swap(a,b):
return b,a
swap(a,b)
22
find duplicates
With this code, you can check if there are duplicate values in the list.
Here I would like to recommend the Python learning Q group I built by myself: 831804576. Everyone in the group is learning Python. If you want to learn or are learning Python, you are welcome to join. Everyone is a software development party and shares dry goods from time to time ( Only related to Python software development),
including a copy of the latest Python advanced materials and zero-based teaching in 2021 that I have compiled by myself. Welcome to the advanced middle and small partners who are interested in Python!