Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ejs94/d2f0cd63b40c0391587a65b336b29976 to your computer and use it in GitHub Desktop.
Save ejs94/d2f0cd63b40c0391587a65b336b29976 to your computer and use it in GitHub Desktop.
Tips from Python Enginner Youtube Channel
# 11 Tips And Tricks To Write Better Python Code
## Source: https://www.youtube.com/watch?v=8OKTAedgFYg
## Python Enginner
# 1) Iterate with enumerate() instead of range(len())
data = [1,2,-4,-3]
for i in range(len(data)):
if data[i] < 0:
data[i] = 0
print(data)
data = [1,2,-4,-3]
for idx, num in enumerate(data):
if num < 0:
data[idx] = 0
print(data)
# 2) Use List of Comprehensions Instead of for raw loops
squares = []
for i in range(10):
squares.append(i*i)
print(squares)
squares = [i*i for i in range(10)]
print(squares)
# 3) Sort Complex iterables with sorted()
data = [3,5,1,10,9]
sorted_data = sorted(data, reverse=True)
print(sorted_data)
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)
# 4) Store unique values with sets
my_list = [1,2,3,4,5,6,7,7,7]
my_set = set(my_list)
print(my_set)
primes = {2,3,5,7,11,13,17,19}
print(primes)
# 5) Save Memory with Generators
import sys
my_list = [i for i in range(10000)]
print(sum(my_list))
print(sys.getsizeof(my_list),"bytes")
my_gen = (i for i in range(10000))
print(sum(my_gen))
print(sys.getsizeof(my_gen),"bytes")
# 6) Define defaults values in Dictionaries with .get() and .setdefault()
my_dict = {"item":"footbal","price": "10.00"}
count = my_dict.get("count")
print(count)
count = my_dict.setdefault("count",0)
print(count)
print(my_dict)
# 7) Count hashable objects with collections.Counter
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(2)
print(counter)
print(most_common)
# 8) Format string with f-Strings
name = "Estevo"
my_string = f"Hello {name}"
print(my_string)
i = 10
print(f"{i} squared is {i*i}")
# 9) Concat string with .join()
list_of_strings = ["Hello","my","friend"]
#BAD!
my_string = ""
for i in list_of_strings:
my_string += i + " "
print(my_string)
# GOOD!
my_string = " ".join(list_of_strings)
print(my_string)
# 10) Merge Dictionaries with {**d1,**d2} (3.5+)
d1 = {"name":"Estevo", "age": 26}
d2 = {"name":"Estevo", "city": "Monte Mor"}
merged_dict = {**d1,**d2}
print(merged_dict)
# 11) Simplify if-statement with if x in [a,b,c]
colors = ["red","green","blue"]
c = "red"
#BAD!
if c=="red" or c== "green" or c=="blue":
print("is main color")
#GOOD!
if c in colors:
print("is main color")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment