Skip to content

Instantly share code, notes, and snippets.

@ngshiheng
Last active February 7, 2022 05:44
Show Gist options
  • Save ngshiheng/8d0aac90db18409b5d8b94ee09a50bf3 to your computer and use it in GitHub Desktop.
Save ngshiheng/8d0aac90db18409b5d8b94ee09a50bf3 to your computer and use it in GitHub Desktop.
def add_book(book_id, storage=[]):
storage.append(book_id)
return storage
my_book_list = add_book(1)
print(my_book_list)
my_other_book_list = add_book(2)
print(my_other_book_list)
# Expectation:
# [1]
# [2]
# Reality:
# [1]
# [1, 2] Huh, what? But they are different variables!
# Do:
def add_book(book_id, storage=None):
if storage is None:
storage = []
storage.append(book_id)
return storage
# Do NOT ever use bare exception:
while True:
try:
input_string = input("Input something")
converted_input = int(input_string)
print(converted_input)
except: # Can't do Ctrl + C to exit!
print("Not a number!")
# NOTE: In Python everything is an object, including list
listA = [1, 2, 3]
listB = [1, 2, 3]
listA is listB # False because they are NOT the same actual object
listA == listB # True because they are equivalent
# Do:
if foo is None:
...
# Don't:
if foo == None:
...
# Do:
if not bar:
...
# Don't:
if bar == False:
...
# Do:
if baz:
...
# Don't:
if baz is True:
...
# Don't
if baz == True:
...
# Don't:
def generate_fruit_basket(fruits):
"""Without list comprehension"""
basket = []
for fruit in fruits:
if fruit != "grapes":
basket.append(fruit)
# Do:
def generate_fruit_basket_lc(fruits):
"""With list comprehension"""
return [fruit for fruit in fruits if fruit != "grapes"]
# Don't:
def get_book_price(inventory):
return [(book, price) for book in inventory if book.startswith('A') for price in inventory[book] if price > 10]
# Perhaps slightly better...? But please don't.
def get_book_price(inventory):
return [
(book, price) for book in inventory
if book.startswith('A')
for price in inventory[book]
if price > 10
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment