Skip to content

Latest commit

 

History

History
146 lines (124 loc) · 3.1 KB

python_cheatsheet.md

File metadata and controls

146 lines (124 loc) · 3.1 KB

Python Tips

Data Structures


Type mutable? ordered?
List mutable ordered
Tuple immutable ordered
Set mutable not ordered
Dictionary mutable not ordered
String / Int immutable

[List]


Sorting
arr.sort(key=len, reverse=True)              # Sorts by length, from longest to shortest
Searching
max(arr,key=len)                             # Find the longest element in list

for i in range(len(nums)-1,-1,-1)            # Following two are equivalent
for i in reversed(range(len(nums))
Operations
arr.insert(index,element)
del arr[index]
arr.remove(element)

nums = nums[::-1]                 # nums changes its reference
nums.reverse()                    # nums reverses the array its referencing
Multiple Assignment
results = [1] * 10
results = [1 for _ in range(10)]
results[0:10:2] = [0]*len(results[0:10:2])  # [0,1,0,1,0,1,0,1,0,1]

{Dictionary}


Searching
max(counter.keys(), key = counter.get)     # Find the highest value out of keys

Deleting mappings

del dict[some_item]

[Other Data Structures]


Set
set.add(4)
set.union(set2)

"String"


Replace / Find / Count
s = s.replace("h","w",3)      # Creates a copy of string and replaces first 3 "h"s to "w"
s.find("ll",5)                # Returns the index of where "ll" is in string after index 5
s.lower().count("e")          # Creates a copy as lowercases and then counts number of "e"s
Operations
s.capitalize()          # First letter is capitalized
s.isalnum()             # Checks alphanumeric character
s.isalpha()             # Checks alphabet character
s.isdecimal()           # Checks decimal character
s.isnumeric()           # Checks numeric

[Other Data Structures]


Set
set.add(4)
set.union(set2)

Python Things


List Comprehension
l = [i for i in range(5)]
Multiple Inheritance
class ArcticBear(Arctic, Bear, Land):
Split / Join
strs = "hello there"    
strs = strs.split(" ")              # ["hello","there"]
strs = " ".join(strs)               # "hello there"
Zip
a = [1,2,3] 
b = [4,5,6]
for i in zip(a,b):
    print(i)     # [(1,4),(2,5),(3,6)]
Map / Filter
nums = [1,2,3,4]
k = map(lambda x : x**2, nums)
print(list(k))     # [1,4,9,16]

nums = [1,2,3,4]
k = filter(lambda x: x%2 == 0, nums)
print(list(k)) 
Changing integer to different formats
bin(x)    # Returns integer x as a string of binary numbers
hex(x)    # Returns integer x as a string of hex (0xffff format)
Random
random.shuffle(nums)                         # randomly shuffles array
random.randint(1,3)                          # random number out of 1,2,3
Iterator
nums = [1,2,3,4,5]
it = iter(nums)
print(next(it))