Initialize array
nums = [0]*10
Print array
nums = [1, 2, 3, 4, 5]print(*nums)
Convert string to char array
chars = list("abc")chars[0] = 'x'
You can access string char using array index, but you can't assign them
text = 'hello'if text[0] == 'h': text[0] = 'x' # error, you can't do character assignment to string
Remove element from list
del nums[index]
Convert char to ascii, and ascii to char
ord('a') # 97chr(97) # a
List index
nums = [1, 2, 3, 4, 5]
First element.
nums[0]
Last element.
nums[-1]
First n elements.
nums[:n]
Last n elements.
nums[-n:]
Insert character
text = 'abde' # insert c -> abcdeindex = 2value = text[:index] + 'c' + text[index:]
Integer overflow
Integer won't overflow in Python (theoretically limited by memory)
import sysvalue = sys.maxsizeprint(value) # 9223372036854775807print(value ** 10) # 4455508415646675013373597242420117818453694838130159772560668808816707086990958982033203334310070688731662890013605553436739351074980172000127431349940128178077122187317837794167991459381249
However, float could overflow.
Python for loop with index
nums = [1, 2, 3, 4, 5]
Python for loop, start from index 0.
NOTE: For technical test, for loop with index is more convinient so you can do things like nums[i] + nums[i+1]
.
for i in range(len(nums)): # 0,1,2,3,4 print(nums[i])
Python for loop, start from index 1.
NOTE: For technical test, for loop with index allow you start start with any index or end with any index.
for i in range(1, len(nums)+1): # 1,2,3,4,5 print(nums[i-1])
Python for loop, reverse fron n-1 to 0.
for i in range(len(nums)-1, -1, -1): # 4, 3, 2, 1, 0 print(nums[i])
Learn more about Python for Loop.
Data Structure
Queue in Python
from collections import dequeq = deque([1, 2, 3]) # initializeq.append(4)q.popleft() # 1q.popleft() # 2
Stack in Python
s = []s.append(1)s.append(2)s.append(3)s.pop() # 3s.pop() # 2s.pop() # 1