I challenged you πŸ†...

You delivered πŸ’ͺ!

I asked you to implement the sum 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.

πŸ‘‡
I didn't get many submissions, so this is going to be a short thread.

The first approach you might feel tempted to follow is by using a `for` loop.

Without too much effort, you can write a pretty clean solution πŸ‘‡
What's good about this solution is that, with no extra effort, it supports the β€œoddβ€œ cases that the built-in `sum` already supports.

For example, I've shown that the built-in `sum` can be used to flatten lists.

So can this implementation:
But there's something else in here.

There's an idea that I'd like to explore.

And it's an idea I wanted you to figure out by yourselves:

`sum`, alongside `all`, `any`, `min`, `max`, `math.prod`, and others is from a very specific family of algorithms!

`sum` is what is called a reduction!

Given a sequence and an operation, a reduction uses that operation to reduce the sequence into a single value.
In the case of `sum`, the operation being used is the addition.

We take a sequence, and reduce it to a single value by summing all the values in the sequence.

In the case of `math.prod`, the operation is multiplication.

For `all`, the operation is `and`.

Etc...
So, once we recognise that `sum` is a reduction, we can actually implement it as such.

That's why many of you suggested an implementation similar to this one πŸ‘‡
By using the `operator` module we don't even need to define a `lambda` that wraps `+`, and our `sum` implementation becomes much more direct and to the point.

Now, many of you will argue that the `for` loop is better because it is simpler...

What do you think? πŸ‘‡πŸ’¬
I prefer to use `reduce` because it tells you, right from the start, the type of algorithm that you used to implement the function.

I like `reduce` so much, I even wrote a whole article explaining how it works, and why it is useful to know about it:

mathspp.com/blog/pydonts/t…

β€’ β€’ β€’

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

30 Oct
πŸπŸ”¦ Python under the hood.

πŸ‘‡πŸ§΅ Here's a thread on the dunder method `__init__`.

You can't say you **know** Python if you don't know this, so...

In this thread we will cover the dunder method `__init__` and its role in Python OOP.

Here we go πŸš€
β€œinit” is short for β€œinitialise” or β€œinitialisation”.

That, right there, tells you what `__init__` is for!

When you create a new instance of a class, you use the method `__init__` to initialise it:

In other words, you use `__init__` to customise the instance.
Here's an example for you.

Say you want to create a class that represents people.

People have names, right? And whenever you create a new person, you want to give them their name.

It will be the __init__'s job, then, to take that name and associate it with the person object.
Read 15 tweets
30 Oct
Want to improve πŸ“ˆ your Python 🐍?

Then STOP πŸ›‘ doing this:

❌ Don't write `for i in range(len(something))`!

βœ… Use `zip` and/or `enumerate`.

You rarely need to iterate over the range of the length of something.

To level up your Python, learn about `zip` and `enumerate`!
In a nutshell, `enumerate` is useful when you need the elements of an iterable *and* the indices as well.

Here is a thread that teaches you the ins and outs of `enumerate`:

In a nutshell, `zip` is useful when you need to iterate over 2 or more iterables *at the same time*.

I also wrote a killer thread about the ins and outs of `zip` a while ago:

Read 4 tweets
15 Oct
You can use Python 🐍 docstrings to provide usage examples of your functions!

That's useful to your users!

And did you know that you can use those examples to do small automatic tests on your functions? 😱

Let me break down how in a mini thread πŸ‘‡πŸ§΅ Image
First off, we define a simple function.

In this case, we just define a function to return the successor of an integer: Image
Then, we define a basic docstring for the function, in a single line.

However, we also add an example showing how using the function looks like.

Notice that the example looks like the REPL: Image
Read 9 tweets
13 Oct
Python 🐍 docstrings πŸ“ are very important, because they are the first level of documentation of your code.

Docstrings are great because IDEs can often display them, to give you help, when you start using a function.

Here's some advice on how to write them πŸ‘‡πŸ§΅
The first line of a docstring should be a short sentence explaining, in English, what the function does.

Write the docstring as a command, not as a long-winded description of what is going to happen.

Go straight to the point, make that line count!
If the function isn't trivial, you need to write a more complete docstring.

Explain what the arguments do and the return value.

Explain what/when the function raises errors.

Let the user know of any side-effects that might happen.

...

Write all of this after a blank line.
Read 4 tweets
13 Oct
🚩🐍 Here's a 4-step roadmap to mastering Python!

The roadmap will take you from complete beginner to building real-world Python apps πŸš€

We'll leverage β€œThe Indie Python Extravaganza”, a πŸ“š bundle that you can get for free during October πŸ‘‰ leanpub.com/b/theindiepyth…

πŸ‘‡πŸ§΅
1. If you are a Python newbie, then I recommend you start with β€œPython 101”, 2nd edition, by @driscollis.

This will teach you the fundamentals of Python!

But if you want to learn how to code, you need to write code!

Makes sense?
2. That's why you should also take a look at β€œPractice Python Projects” by @learn_byexample, which will have you write small projects.

This will be very important for you to develop a level of comfort with writing Python code!

Next up, you want to write the best code possible!
Read 8 tweets
9 Oct
Everyone knows that giving proper names to variables and functions is the true programmer's bane.

Here's a thread πŸ‘‡πŸ§΅ with do's and don'ts for naming things in Python 🐍

We can only hold a small number of simultaneous ideas in our 🧠, so proper naming can really help us!
There exist a bunch of naming conventions out there.

Some of them are more common in Python, and others are rarely seen in Python code.

Let me just show you what they look like, and then I'll walk you through when you could use each.
The PascalCase convention is often used with classes.

Notice that when you use PascalCase, you should uppercase all letters of an acronym πŸ‘‡

In the image, that's exemplified by the `AIPlayer`, where `AI` stands for β€œartificial intelligence”.
Read 21 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!

:(