Common used functions in Python

index()

The index() method returns the index of the specified element in the list.

1
2
3
4
5
6
7
8
animals = ['cat', 'dog', 'rabbit', 'horse']

# get the index of 'dog'
index = animals.index('dog')

print(index)

# Output: 1

set()

1
2
3
4
5
6
triplets = set() # automatically remove duplicates
triplets.add((1,2,3))
triplets.add((1,2,4))
triplets.add((1,2,3))
print(triplets)
# output: {(1, 2, 3), (1, 2, 4)}

isalnum()

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
continue
if not s[right].isalnum():
right -= 1
continue

if s[left].lower() != s[right].lower():
return False

left += 1
right -= 1

return True

ord()

ord() function returns the Unicode code from a given character.

1
print(ord('a')) # 97

bin()

bin() function returns the binary string of a given integer.

1
2
3
n=12 # 1100
countOnesInStr=bin(n).count("1")
print(countOnesInStr)

zip()

zip() method takes iterable containers and returns a single iterator object, having mapped values from all the containers.

It is used to map the similar index of multiple containers so that they can be used just using a single entity.

Syntax : zip(*iterators)

Parameters : Python iterables or containers ( list, string etc )
Return Value : Returns a single iterator object.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fruit = [ "apple", "orange", "banana", "pear" ]
amount = [ 4, 1, 3, 2 ]

# using zip() to map values
mapped = zip(fruit, amount)

print(set(mapped))
# output: {('banana', 3), ('pear', 2), ('apple', 4), ('orange', 1)}

print(mapped)
for f, a in mapped:
print(f,a)
# output:
# <zip object at 0x7fa50d60d480>
# apple 4
# orange 1
# banana 3
# pear 2

random.randint()

random.randint() return random integer in range [a,b] inclusively.

1
2
3
4
import random

# return random integer in [0,10]
random.randint(0, len(self.nums) - 1)

random.choice()

random.choice() chooses a random element from non-empty sequence.

1
2
3
import random
charset = "abcdefghijklmnopqrstuvwxyxABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
print("".join([random.choice(charset) for _ in range(4)])) # 1H0N

strip()

The strip() method removes any leading, and trailing whitespaces.

1
2
3
txt = "     banana     "

x = txt.strip()

bisect.bisect_left()

Return the index where to insert item x in list a, assuming a is sorted.

1
2
3
import bisect
arr=[1,3,4,6,7,9,10,12]
insertIdx = bisect.bisect_left(arr, 8) # 5

slice operations

1
2
3
4
5
6
7
8
9
10
11
12
13
s="abcdefcd"

# reverse string
print(s[::-1]) # dcfedcba

# count substring
print(s.count(s[2:4])) # 2

# last k elements
print(s[-2:]) # cd

# repeat string
print(s * 2) # abcdefcdabcdefcd

Dictionary pop()

pop() method removes and returns an element from a dictionary having the given key.

1
2
3
4
5
marks = { 'Physics': 85, 'Chemistry': 90, 'Math': 100 }

element = marks.pop('Math')

print('Popped Marks:', element)# Popped Marks: 100

heapq

1
2
3
4
import heapq
minHeap = [(2, (0, 0)),(4, (1, 0)),(1, (2, 4))]
heapq.heapify(minHeap)
print(minHeap[0]) # (1, (2, 4))

To remove particular item in heap:

1
2
3
4
5
6
7
8
9
print(minHeap) # [(1, (2, 4)), (4, (1, 0)), (2, (0, 0))]

# replace the target item with the last item
minHeap[0] = minHeap[-1]
# remove the target item from list
minHeap.pop()
# re-heapify the list
heapq.heapify(minHeap)
print(minHeap) # [(2, (0, 0)), (4, (1, 0))]

sort with lambda

1
2
3
4
5
6
7
arr = [(1,3),(4,2),(6,4),(3,5)]
arr.sort(key=lambda x: x[1], reverse=True)
print(arr) # [(3, 5), (6, 4), (1, 3), (4, 2)]

# Or:
# arr.sort(key=lambda x: -x[1])
# print(arr) # [(3, 5), (6, 4), (1, 3), (4, 2)]

list pop() and insert()

1
2
3
4
5
arr = [1,2,3,4,5]
arr.pop(3)
print(arr) # [1, 2, 3, 5]
arr.insert(3,4)
print(arr) # [1, 2, 3, 4, 5]

check if integer

1
2
3
4
5
6
7
8
print(type(10) is int) # True

print(type(10.0) is int) # False

print(isinstance(10, int)) # True

n=10.0
print(isinstance(n, float) and n.is_integer()) # True

check if string is a decimal

1
2
3
4
5
6
7
8
s="123"
num = 0
i = 0
while i < len(s) and s[i].isdecimal():
num = 10 * num + int(s[i])
i += 1

print(num)

reduce()

https://thepythonguru.com/python-builtin-functions/reduce/

The reduce() function accepts a function and a sequence and returns a single value calculated as follows:

Initially, the function is called with the first two items from the sequence and the result is returned.
The function is then called again with the result obtained in step 1 and the next value in the sequence. This process keeps repeating until there are items in the sequence.
The syntax of the reduce() function is as follows:

Syntax: reduce(function, sequence[, initial]) -> value

1
2
3
4
5
6
7
8
9
10
from functools import reduce # only in Python 3
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# hint: xor the same number results in 0
#res = nums[0]
#for i in range(1,len(nums)):
# res ^= nums[i]
#return res

return reduce(lambda res, num: res ^ num, nums)