πŸ†Β Here's a mini Python 🐍 challenge.

You have an int `value` and a dictionary `my_dict`.

`my_dict` **may** contain a key `"field"`, with an int.

If `"field"` is there, add it to `value`.

How would you solve this?

Here's a short thread πŸ‘‡πŸ§΅ with a couple of solutions.
First off, this mini thread was prompted by @svpino's most recent tweet, that I include here for credit and context:

Like Santiago pointed out, there are two archetypes of solutions here.

The first one, is to check if the `"field"` is there, and then add to `value`.

Simple to understand, but with one β€œdrawback” that bothers me just a little bit... Image
And that's the fact that we are essentially looking into the dictionary twice.

Once to check if the key is there, and then again to get the value associated with the key (when the key is there).

This is the typical β€œLook Before You Leap” (LBYL) coding style: check before doing.
There is another fundamentally different approach, often considered idiomatic in Python:

β€œEasier to Ask Forgiveness than Permission” (EAFP)

That's essentially: just do whatever you want. Say you are sorry only if it goes wrong.

In Python code, use a `try: ... except: ...` πŸ‘‡ Image
Python has great syntax to support the EAFP coding style, and there are some notorious examples of where EAFP is a better approach.

I wrote about it in this article πŸ‘‡

But this thread is not about the LBYL vs EAFP discussion.

It's about something else.

mathspp.com/blog/pydonts/e…
This thread is about keeping your code simple and trying to avoid unnecessary flow control.

Both approaches πŸ‘† have some flow control that shows in the form of indentation.

Wouldn't it be nice if you could just do the addition, regardless of whether the field is there?
Well, using the dictionary `.get` method, you can!

You can just use it to fetch the field and give a default value of `0` πŸ‘‡

Why `0`? Because adding `0` does nothing!

This is a pattern that can be exploited often, but people don't use... Image
When you want to get something from a dictionary, and that thing may or may not be there...

And then you want to use it IF it was there...

Try using this approach.

Figure out if there is a value that would act as a β€œno-op”, and return it from the dictionary with `.get`.
In the case above, the β€œno-op” to addition (the identity element, as we call it in maths) was the 0.

Why?

Because β€œsomething plus 0” is always β€œsomething”.

Or, in other words, doing β€œplus 0” leaves the input unchanged.

Makes sense?

Here's the 3 approaches stacked πŸ‘‡ Image
So, of these three alternatives we looked at, which one do you think is the best?

If you come up with another alternative that you think brings something to the table, share it with us as well!

β€’ β€’ β€’

Missing some Tweet in this thread? You can try to force a refresh
γ€€

Keep Current with Rodrigo πŸπŸ“

Rodrigo πŸπŸ“ Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @mathsppblog

7 Oct
Python 🐍 dictionaries are amazing ✨ data structures.

Do you know how to make the best use out of them?

One method you should have in your arsenal is the `.get` method.

Here's a short thread πŸ‘‡πŸ§΅ about it. Image
A dictionary is a β€œmapping”: it maps keys into values.

In Python, if you have a key, you can use it inside `[]` to access the corresponding value πŸ‘‡

However, ... Image
... if the key doesn't exist, then you get an error!

As an example, here's my attempt at getting my age from the previous dictionary, which only knew about my name πŸ‘‡

So, how to try and access keys without having Python throw an error at your face..? Image
Read 12 tweets
4 Oct
What's the deal with Python 🐍's pass-by-value or pass-by-reference?

How does it relate to mutable and immutable objects?

Here's a Python thread πŸ‘‡πŸ§΅ that'll make everything crystal clear and help you master Python 🐍.

Let's go πŸš€
First thing you need to realise is that Python 🐍 does not use the pass-by-value model...

But it also does not use the pass-by-reference model!

Let me see if I can explain what I mean!

What does it mean to pass by value?
In the pass-by-value model, whenever you call a function with a given argument, that argument is fully copied into the function.

This means you can change what got into your function, and you won't be able to see the changes from the outside.

This _looks_ like pass-by-value:
Read 26 tweets
2 Oct
πŸ› πŸ‘€ On the 23/09 I challenged myself to go from 2.95k followers to 4k by the end of the month 😱

That was +1.05k followers (+36%) in 7 days.

On the 1st Oct I woke up to a little over 6k followers πŸŽ‰πŸ”₯ that's INSANE!

Thanks for your support!

Here's a recap of these days πŸ‘‡πŸ§΅
First off, for reference, here is the original tweet with the public challenge:

In the original tweet I said that my strategy would be to publish a high-value thread each day.

For my challenge to be met, I had to grow β‰ˆ4% each day.

Here's a breakdown of the number of followers I woke up to each day, with the % change relative to the previous day.
Read 13 tweets
2 Oct
I love the `enumerate` Python 🐍 built-in!

I love it because your `for` loops become much more readable ✨ if you know how to use it.

Here's a thread πŸ‘‡πŸ§΅ on how `enumerate` will make your Python code so much better.

Let's go πŸš€
Python's `for` loops are amazing!

And yet, many people write too much stuff in their loops.

For example, if you just need to go through a list, you shouldn't be writing this πŸ‘‡
In Python, you can just β€œgo through lists”, you don't need to compute the range of the length of the list!

Instead of the above, you can just write this πŸ‘‡

This is better because you can read it as β€œfor each colour in the list `l`”.
Read 16 tweets
30 Sep
β€œBe consistent”, they say.

But why?

Have you ever heard of the compounding effect?

Or exponential growth?

I'll show you how all these are connected, with real-life examples πŸ‘‡πŸ§΅ Image
I'll let you in on a little secret: I have a personal goal on Twitter.

The goal is to grow by 1% every day.

That's just that.

Every day, I want my follower count to increase by 1%

If you are anything like me, you might be thinking:
β€œIsn't 1% too little? You're gonna take ages to grow!”

Well...

Is 1% that little?

I'll show you it isn't!

First, here's a screenshot of my growth in the beginning of my Twitter journey πŸ‘‡

Let's work with those numbers... Image
Read 32 tweets
29 Sep
I challenged you πŸ†...

You delivered πŸ’ͺ!

I asked you to implement the sign function in Python 🐍.

Now I'll go over some alternatives and tell you what I like βœ… and dislike ❌ about them.

I'll also tell you which one I think is the best, most Pythonic ✨ one.

πŸ‘‡πŸ§΅
By the way, for reference, here is the original challenge:

Let's start with the β€œbasic” `if: ... elif: ... else: ...` approach first.

Gets the job done, is simple, and is easy to ready.

Funnily enough, the only one to share that solution was a _very_ seasoned Python 🐍 programmer, author and trainer, @dabeaz πŸ™ƒ

Now, a couple of notes:
Read 28 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(