/ division
// floor division. division is done as an integer, with the floor returned.
As Dictionary and Sets both use { }, if creating a blank type, eg fruits = {}, it is ambigious as to if it's a dictionary or set, so use fruits = set() to create a blank set.
Quick Examples
# List
fruits = ["apple", "banana", "grape"]
print (fruits[1]) # banana
# Dictionary
car = {
"brand": "Holden",
"model": "Commodore",
"cylinders": 8
}
print (car["brand"]) # Holden
# Set
fruits = {"apple", "banana", "grape"}
print (fruits[1]) # banana
names = []
names.append("biggus")
names.append("dickus")
num = [1,2,3,4,5,6,7,8]
del nums[4]
# 1,2,3,4,6,7,8
num = [1,2,3,4,5,6,7,8]
del nums[1:3]
# 1,4,5,6,7,8
del nums[:] #delete all elements
The opposite of .append
Removes an item of a list and returns it to whatever called it.
By default, removes last item, or whatever index is supplied
names = ["biggus","dickus"]
lastname = names.pop()
// lastname = "dickus"
veggies = ["broccoli","cabbage","carrot"]
bigveggie = veggies.pop(1)
// bigveggie = "cabbage"
names = ["biggus","dickus"]
print ("biggus" in names)
// True
Add to a set
fruits = set()
fruits = {"apple","grape"}
fruits.add("fat banana")
Delete from a set
fruits.remove("fat banana")
You can subtract one set away from another
set1 = {"apple", "banana", "grape"}
set2 = {"apple", "banana"}
set3 = set1 - set2
print(set3)
# Prints: {'grape'}
You can convert between lists and sets
List to Set uses set()
Set to List uses list()
Are immutable sequences
When you're returning multiple values from a function, you are returning a tuple
myTuple = ("this is a tuple", 69, True)
print(myTuple[0])
# this is a tuple
Tuples can be stored in a list
my_tuples = [
("first tuple", 4, False),
("second tuple", 69, True)
]
print(my_typles[1][1]) # 69
Unpacking a tuple
dog = ("Fido", 10)
dog_name, dog_age = dog
Similar to maps in Go. key value pairs
Define a dictionary
car = {
"brand": "Holden",
"model": "Commodore",
"cylinders": 8
}
# Retrieve from a string using it's key
print(car["brand"])
# Add a key to a dictionary
car["colour"] = "black"
# Delete a key. Will get an error if key doesn't exist
del car["colour"]
# Check if a key exists
print("colour" in car)
# False
Concat with a +
or use an f string
firstname = "Biggus"
lastname = "Dickus"
#Below do the same
print(firstname + " " + lastname)
print(f"{firstname} {lastname}")
Join strings
string_list = ["go","and","get"]
print (" ".join(string_list))
items = ["potion", "bread", "sword"]
for i in range(0, len(items):
print(items[i]
// Better way
for item in items:
print(item)
Catch exceptions with try/except blocks
Use raise to trigger your own exceptions.
try:
do_stuff()
do_more_stuff()
except Exception as e:
print(e)
def do_stuff():
print("stuff")
raise Exception("stuff is borked")
You can setup different exceptions handlers for different exceptions, and have a generic one that covers all other cases.
Put specific exception handlers first. In the 2nd example belowm, the IndexError handler won't ever get called.
try:
10/0
except ZeroDivisionError:
print("0 division")
except Exception as e:
print(e)
try:
num = [0, 1]
print(num[3])
except Exception:
print("Some exception occurred")
except IndexError:
print("Index error") # This won't work. Needs to be put before the general exception handler
def binary_search(target, arr):
low = 0
high = len(arr)-1
while low <= high:
median = int((low + high) / 2)
if arr[median] == target:
return True
if arr[median] < target:
low = median + 1
else:
high = median - 1
return False