100% found this document useful (1 vote)
138 views6 pages

Python Cheat Sheet Made by Abdul Malik

This document provides a cheat sheet for common Python data structures and algorithms. It describes lists, dictionaries, counters, deques, heaps, sets, tuples and built-in functions like map, zip, any, enumerate, filter and bisect. For each data structure, it lists common operations and time complexities.

Uploaded by

Raji Rayapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
138 views6 pages

Python Cheat Sheet Made by Abdul Malik

This document provides a cheat sheet for common Python data structures and algorithms. It describes lists, dictionaries, counters, deques, heaps, sets, tuples and built-in functions like map, zip, any, enumerate, filter and bisect. For each data structure, it lists common operations and time complexities.

Uploaded by

Raji Rayapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Python Cheat Sheet Made by Abdul Malik

💡 Portfolio Website : https://www.maliksquared.com/

Data Structures
Important data structures for Leetcode

Lists

Lists are used to store multiple items in a single variable

Operations Time Complexities

nums = [1,2,3]

nums.index(1) # returns index


nums.append(1) # appends 1
nums.insert(0,10) # inserts 10 at 0th index
nums.remove(3) # removes all instances of 3
nums.copy(1) # returns copy of the list
nums.count(1) # returns no.of times '1' is present in the list
nums.extend(someOtherList) # ...
nums.pop() # pops last element [which element to pop can also be given as optional argument]
nums.reverse() # reverses original list (nums in this case)
nums.sort() # sorts list [does NOT return sorted list]

Python Cheat Sheet Made by Abdul Malik 1


Dictionary
Dictionaries are used to store data values in key:value pairs. Info about collections.Counter() available below.

Operations Time Complexities

dict = {'a':1,'b':2,'c':3}

dict.keys() # returns list of keys of dictionary


dict.values() # returns list of values of dictionary
dict.get('a') # returns value for any corresponding key
dict.items() # returns [('a',1),('b',2),('c',3)]
dict.copy() # returns copy of the dictionary
# NOTE : items() Returns view object that will be updated with any future changes to dict
dict.pop(KEY) # pops key-value pair with that key
dict.popitem() # removes most recent pair added
dict.setDefault(KEY,DEFAULT_VALUE) # returns value of key, if key exists, else default value returned
# If the key exist, this parameter(DEFAULT_VALUE) has no effect.
# If the key does not exist, DEFAULT_VALUE becomes the key's value. 2nd argument's default is None.
dict.update({KEY:VALUE}) # inserts pair in dictionary if not present, if present, corresponding value is overriden (not key)
# defaultdict ensures that if any element is accessed that is not present in the dictionary
# it will be created and error will not be thrown (which happens in normal dictionary)
# Also, the new element created will be of argument type, for example in the below line
# an element of type 'list' will be made for a Key that does not exist
myDictionary = defaultdict(list)

Python Cheat Sheet Made by Abdul Malik 2


Counter
Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a
sub-class available inside the dictionary class. Specifically used for element frequencies

Pretty similar to dictionary, infact I use defaultdict(int) most of the time

from collections import Counter #(capital 'C')


# can also be used as 'collections.Counter()' in code

list1 = ['x','y','z','x','x','x','y', 'z']

# Initialization
Counter(list1) # => Counter({'x': 4, 'y': 2, 'z': 2})
Counter("Welcome to Guru99 Tutorials!") # => Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2.....})

# Updating
counterObject = collections.Counter(list1)
counterObject.update("some string") # => Counter({'o': 3, 'u': 3, 'e': 2, 's': 2})
counterObject['s'] += 1 # Increase/Decrease frequency

# Accessing
frequency_of_s = counterObject['s']

# Deleting
del couterObject['s']

Deque
A double-ended queue, or deque, has the feature of adding and removing elements from either end.

Operations Time Complexities

from collections import deque

queue = deque(['name','age','DOB'])

queue.append("append_from_right") # Append from right


queue.pop() # Pop from right

queue.appendleft("fromLeft") # Append from left


queue.popleft() # Pop from left

queue.index(element,begin_index,end_index) # Returns first index of element b/w the 2 indices.


queue.insert(index,element)
queue.remove() # removes first occurrance
queue.count() # obvious

queue.reverse() # reverses order of queue elements

Python Cheat Sheet Made by Abdul Malik 3


Heapq
As we know the Heap Data Structure is used to implement the Priority Queue ADT. In python we can directly access a
Priority Queue implemented using a Heap by using the Heapq library/module.

Operations Time Complexities

import heapq # (minHeap by Default)

nums = [5, 7, 9, 1, 3]

heapq.heapify(nums) # converts list into heap. Can be converted back to list by list(nums).
heapq.heappush(nums,element) # Push an element into the heap
heapq.heappop(nums) # Pop an element from the heap
#heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained.
#heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained.

# Rarely used methods


# Used to return the k largest elements from the iterable specified
# and satisfying the key (if is is mentioned).
heapq.nlargest(k, iterable, key = fun)
heapq.nsmallest(k, iterable, key = fun)

Python Cheat Sheet Made by Abdul Malik 4


Sets
A set is a collection which is unordered, immutable, unindexed, No Duplicates.

Operations Time Complexities

set = {1,2,3}

set.add(item)
set.remove(item)
set.discard(item) | set.remove(item) # removes item | remove will throw error if item is not there, discard will not
set.pop() # removes random item (since unordered)

set.isdisjoint(anotherSet) # returns true if no common elements


set.issubset(anotherSet) # returns true if all elements from anotherSet is present in original set
set.issuperset(anotherSet) # returns true if all elements from original set is present in anotherSet

set.difference(anotherSet) # returns set containing items ONLY in first set


set.difference_update(anotherSet) # removes common elements from first set [no new set is created or returned]
set.intersection(anotherSet) # returns new set with common elements
set.intersection_update(anotherSet) # modifies first set keeping only common elements
set.symmetric_difference(anotherSet) # returns set containing all non-common elements of both sets
set.symmetric_difference_update(anotherSet) # same as symmetric_difference but changes are made on original set

set.union(anotherSet) # ...
set.update(anotherSet) # adds anotherSet without duplicate

Python Cheat Sheet Made by Abdul Malik 5


Tuple

A tuple is a collection which is ordered, unchangeable and can contain duplicate values

Operations Time Complexities


Similar to list

tuple = (1,2,3,1)

tuple.count(1) # returns occurence of an item


tuple.index(1) # returns index of 1 in array

Built-in or Library functions

** map(fun, iter) **
#fun : It is a function to which map passes each element of given iterable.
#iter : It is a iterable which is to be mapped.

** zip(list,list) **
for elem1,elem2 in zip(firstList,secondList):
# will merge both lists and produce tuples with both elements
# Tuples will stop at shortest list (in case of both lists having different len)

** any(list) ** [ OPPOSITE IS => ** all() ** ]


any(someList) # returns true if ANY element in list is true [any string, all numbers except 0 also count as true]

** enumerate(list|tuple) **
# [when you need to attach indexes to lists or tuples ]
enumerate(anyList) # ['a','b','c'] => [(0, 'a'), (1, 'b'), (2, 'c')]

** filter(function|list) **
filter(myFunction,list) # returns list with elements that returned true when passed in function

***************** import bisect ***********************

** bisect.bisect(list,number,begin,end) ** O(log(n))
# [ returns the index where the element should be inserted
# such that sorting order is maintained ]
a = [1,2,4]
bisect.bisect(a,3,0,4) # [1,2,4] => 3 coz '3' should be inserted in 3rd index to maintain sorting order

# Other variants of this functions are => bisect.bisect_left() | bisect.bisect_right()


# they have same arguments. Suppose the element we want to insert is already present
# in the sorting list, the bisect_left() will return index left of the existing number
# and the bisect_right() or bisect() will return index right to the existing number

# ** bisect.insort(list,number,begin,end) ** O(n) to insert


# ** bisect.insort_right(list,number,begin,end) **
# ** bisect.insort_left(list,number,begin,end) **

The above 3 functions are exact same of bisect.bisect(), the only difference
is that they return the sorted list after inserting and not the index. The
left() right() logic is also same as above.

** ord(str) **
# returns ascii value of the character , Example ord("a") = 97
** chr(int) **
#return character of given ascii value , Example chr(97) = "a"

Python Cheat Sheet Made by Abdul Malik 6

You might also like