-
Notifications
You must be signed in to change notification settings - Fork 0
Python Code Tips
Bad way
data = [1,2,-4,-3]
for i in range(len(data)):
if data[i] <0 :
data[i] = 0
print(data)Better way
data = [1,2,-4,-3]
for idx, num in enumerate(data):
if num < 0:
data[idx] = 0
print(data)Bad Way; if super short and is not readable
squares = []
for i in range(10):
squares.append(i*i)
print(squares)Better way; if super short and is not readable
squares = [i*i for i in range(10)]
print(squares)List comprehension example
connections = [conn for conn in some_list]
Simple iterable sorting using list
data = [3,5,1,10,9]
sorted_data = sorted(data)
print(sorted_data)Complex iterable sorting using dict of list
data = [ {"name": "max", "age" : 6},
{"name": "lisa", "age" :20},
{"name": "ben", "age" :9}]
sorted_data = sorted(data, key=lambda x: x["age"])
print(sorted_data)my_list = [1,2,3,4,5,6,7,7,7]
my_set = set(my_list)
print(my_list)
primes = {2,3,5,7,11,13,17,19}
print(primes)connections = (conn for conn in some_list)my_dict = {"item": "football", "price": 10.00}
count = my_dict.get("count", 0)
print(count)
count = my_dict.setdefault("count", 0)
print(count)https://docs.python.org/3/library/collections.html#collections.Counter
Print the counts of all lists
from collections import Counter
my_list = [10,10,10,5,5,2,9,9,9,9,9,9]
counter = Counter(my_list)
print(counter)Find the most common
from collections import Counter
my_list = [10,10,10,5,5,2,9,9,9,9,9,9]
counter = Counter(my_list)
most_common = counter.most_common(1)
print(most_common)Find the least common
from collections import Counter
my_list = [10,10,10,5,5,2,9,9,9,9,9,9]
counter = Counter(my_list)
least_common = counter.most_common()[-1]
print(least_common)name = "Bob"
my_string = f"Hello {name}"
print(my_strin)strings_to_join = ["Join", "this", "string"]
message = " ".join(strings_to_join)
print(message)
Join this stringhttps://towardsdatascience.com/merge-dictionaries-in-python-d4e9ce137374
d1 = {"name": "Alex", "age": 25}
d2 = {"name": "Alex", "city": "New York"}
merged_dict = {**d1, **d2}
print(merged_dict)colors = ["red", "green", "blue"]
c = "red"
if c in colors:
print(f"{c} is main color")Use vars() to enuermtae objects with properties into dictionaries
class Example:
def __init__():
self._name = None
@property
def name(self)
try :
return self._name
except Exception as e:
raise e
example = Example()
print(vars(example))
{"_name" : None }1.) Ternary Conditionals Instead of the following
condtion = True
if condition:
x = 1
else:
x = 0You can write this one oneline with Ternary Conditionals
condition = True
x = if condition else 02.) Unerscore Placholers with large numbers
num1 = 10_000_000_000Seperators in output
num1 = 10_000_000_000
num2 = 100_000_000
total = num1 + num2
print(f'{total:,}')
10,100,000,0003.) Context Managers Bad smell, the code works but you want to use context managers for auto closing
f = open('test.txt', 'r')
file_contents = f.read()
f.close()
words = file_contents.split(' ')
word_count = len(words)
print(word_count)Context manager
with open('test.txt', 'r') as f:
file_contents = f.read()
words = filel_contents.split(' ')
word_count = len(words)
print(word_count)**not just for files, can be with databases or anything with managing resources and requiring some type of setup and shutdown. 4.) Enumerate Looping but manually keeping up with the index
names = ['Bob', 'Doyle', 'Joe']
index = 0
for name in names:
print(index, name)
index += 1Enumerate, keeps up with index automatically
names = ['Bob', 'Doyle', 'Joe']
for index, name in enumerate(names):
print(index,name)5.) Zip Looping through two lists that correspond
names = ['Peter Parker', 'Clark Kent', 'Wade Wilson', 'Bruce Wayne']
heroes = ['Spiderman', 'Superman', 'Deadpool', 'Batman']
for index, name in enumerate(names):
hero = heroes[index]
print(f"{name} is actually {hero}")Using zip instead of enumerate
names = ['Peter Parker', 'Clark Kent', 'Wade Wilson', 'Bruce Wayne']
heroes = ['Spiderman', 'Superman', 'Deadpool', 'Batman']
for name, hero in zip(names, heroes):
print(f"{name} is actually {hero}")6.) Unpacking Zip actual returns a tuple and in the previous example we were unpacking
# Packed example
names = ['Peter Parker', 'Clark Kent', 'Wade Wilson', 'Bruce Wayne']
heroes = ['Spiderman', 'Superman', 'Deadpool', 'Batman']
for value in zip(names, heroes):
print(value)
('Peter Parker, Spiderman)Unpacking exmaple
a, b = (1,2)
print(a)
print(b)Unpacking but only using one value
a, _ = (1, 2)
print(a)Unpack with more than exists
a,b,c = (1,2) #ValueError not enough values to unpack (expected 3, got 2)
a,b,c = (1,2,3,4,5) #ValueError too many values to unpack (expected 3)
a, b, *c = (1 ,2, 3, 4, 5) # by putting an * in front of C c gets allthe other values
a,b,*_ = (1,2,3,4,5) #ignores everything else after a,b
a,b,*c,d = (1,2,3,4,5) #a,b set to first two values, d is set to last, c has the values in the middle7.) Setattr/Getattr Initiall python uses dynmaic attributes
class Person():
pass
person = Person()
# dynamic attributes in python
person.first = "Bob"
person.last = "Doyle"Using setattr directly you can use variables
class Person():
pass
first_key = "first"
first_val = "Bob"
setattr(person, first_key, first_val)Using setattr to set the person attributes
class Person():
pass
person = Person()
person_info = {'first': 'Corey', 'last': 'Schafer'}
for key, value in person_info.items():
setattr(person, key, value)Using getattr to retrive keys
class Person():
pass
person = Person()
person_info = {'first': 'Corey', 'last': 'Schafer'}
for key, value in person_info.items():
setattr(person, key, value)
for key in person_info.keys():
print(getattr(person, key))8.) Getpass Typing in secret values
Wrong way
username = input('Username: ')
password = input('Password: ')
Print('Logging in...)Better way with getpass
from getpass import getpass
username = input('Username: ')
password = getpass('Password: ')
print('Logging in...)9.) Python dash m What happens with the -m option?
# Creating a virtual environment with venv module
python -m venv .venv
# Start debug server
python -m smtpd -c DebuggingServer -n localhost:1025-m search sys.path for the named module and execute contents like main module
10.) Help/Dir
python
>>>help # interactive help in python interpreter
>>>help(http) # help on specific modulesdir(http) #returns a list of valid attributes for the object passed