Common used functions in Python
index()
The index() method returns the index of the specified element in the list.
1 | animals = ['cat', 'dog', 'rabbit', 'horse'] |
set()
1 | triplets = set() # automatically remove duplicates |
isalnum()
The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
1 | class Solution: |
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 | n=12 # 1100 |
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 | fruit = [ "apple", "orange", "banana", "pear" ] |
random.randint()
random.randint() return random integer in range [a,b] inclusively.
1 | import random |
random.choice()
random.choice() chooses a random element from non-empty sequence.
1 | import random |
strip()
The strip() method removes any leading, and trailing whitespaces.
1 | txt = " banana " |
bisect.bisect_left()
Return the index where to insert item x in list a, assuming a is sorted.
1 | import bisect |
slice operations
1 | s="abcdefcd" |
Dictionary pop()
pop() method removes and returns an element from a dictionary having the given key.
1 | marks = { 'Physics': 85, 'Chemistry': 90, 'Math': 100 } |
heapq
1 | import heapq |
To remove particular item in heap:
1 | print(minHeap) # [(1, (2, 4)), (4, (1, 0)), (2, (0, 0))] |
sort with lambda
1 | arr = [(1,3),(4,2),(6,4),(3,5)] |
list pop() and insert()
1 | arr = [1,2,3,4,5] |
check if integer
1 | print(type(10) is int) # True |
check if string is a decimal
1 | s="123" |
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 | from functools import reduce # only in Python 3 |