Things that weren't so obvious when you started to program in Python

henbaku

Edgar Darío

Posted on December 21, 2017

Things that weren't so obvious when you started to program in Python

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"
Enter fullscreen mode Exit fullscreen mode

Nothing simpler than putting:

some = "Dafaq" if x < 56 else "Nope"
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Best way:

a = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34] # example list.
b = [i for i in a if i >= 15]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Best way:

amounts = [2, 24, 88, 32, 1, 6, 88, 10, 15, 34]
total = sum(amounts)
Enter fullscreen mode Exit fullscreen mode

In the next chapter...

Things that weren't so obvious when you starting to using Django...

💖 💪 🙅 🚩
henbaku
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.

Related