Things that weren't so obvious when you started to program in Python
Edgar Darío
Posted on December 21, 2017
I introduced myself in the programming world using very basic languages. Since 4 years ago, I created many many projects using Python, but although the Python Zen says "There should be one-- and preferably only one --obvious way to do it.", some things aren't obvious.
One line conditionals.
My old code has too redundant code, specially with conditionals:
if x < 56:
some = "Dafaq"
else:
some = "Nope"
Nothing simpler than putting:
some = "Dafaq" if x < 56 else "Nope"
One line filtering lists.
One of the most common situations in Python is "filtering" lists. My old way:
a = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34] # example list.
b = []
for i in a:
if i >= 15:
b.append(i)
Best way:
a = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34] # example list.
b = [i for i in a if i >= 15]
One line sum list values.
Other of the most common things is to sum up the values of a list. My old way:
amounts = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34] # example list.
total = 0
for i in amounts:
total += i
Best way:
amounts = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34]
total = sum(amounts)
In the next chapter...
Things that weren't so obvious when you starting to using Django...
💖 💪 🙅 🚩
Edgar Darío
Posted on December 21, 2017
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.