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:
This looks like pass-by-value because we put `a` inside the function, and it had the value `3`.

Then, the function changed to the value `4`...

But outside of the function, `a` is still 3.

This is why it may look like Python uses pass-by-value...

But it doesn't:
And Python does NOT use pass by value because we can do things like this πŸ‘‡

Notice that, in this example, I was able to make a change that reflected outside of the function!

So, is this pass-by-reference..?
This is also _not_ pass-by-reference!

In the pass-by-reference model, the called function would get access to the callee's variables!

Notice this is not what is happening, as I cannot _change_ the variable `l` outside the function πŸ‘‡

Notice how `l` stays the same.
This is different, for example, from this Pascal code πŸ‘‡

The code below outputs the following:

```
2
6
```

Notice how the value of `a` actually changed outside of the function just by means of a simple assignment.
(By the way, you can try this Pascal code by following the link πŸ”— tio.run/##lZAxDsIwDEV3… to the tio.run website.)
Alright, so Python is not pass-by-value and also not pass-by-reference, so what is it..?

Well, in order to understand what Python does, we need to understand well what Python objects are!

By the way, did you know that everything in Python is an object?
Each Python object is characterised by three things...

πŸ‘‰ its identity (an integer that identifies your object, just like your social security number);
πŸ‘‰ a type (that identifies what operations you can do with your ojbect); and
πŸ‘‰ some content;

Here's an example πŸ‘‡
Now, what might be tricky here, is that the β€œname” `obj` has NOTHING to do with the object itself.

The three letters β€œobj” were just a label that I attached to the object with identity 2698212637504, type list, and contents 1, 2, 3.

I can attach many names to it πŸ‘‡
But these names are just labels I put on the exact same object.

How can I know it's the exact same object?

Well, all their β€œsocial security numbers” match πŸ‘‡

Therefore, these labels all point to the same name...

So...
Oh, and by the way, this is what the `is` operator does in Python 🐍!

It checks to see if two labels (two names) are pointing at the _same_ object.

In other words, it checks if the identities of the two operands are the same!
So this is what assignment does: it just sticks a new label – a new name – onto an object.

It's pretty much like a nickname!

I have plenty of different nicknames, but regardless of what you call me, or what my mom calls me, I'm always the same person, right..?
Therefore, if I change, everyone sees the change, not just my mom, or not just my friends, or not just you!

So, if I mutate the _contents_ of the list we had previously...

Then all the nicknames should be able to tell that something is different πŸ‘‡
Now, at this point, the identity of the object did NOT change!

It's still the same object!

It's just that its contents changed a bit.

Much like you can change your clothes, or have different thoughts.

That's because a list is a _mutable_ object..!
_Mutable_ means that it can be mutated – that it can be changed (internally).

Some other Python types are _immutable_, which means they cannot be modified internally.

A good example of that is the `tuple` type.

If you create a `tuple`, you can't change its elements πŸ‘‡
Thus, with immutable data types (like tuples, strings, integers, floats) you can only _build_ new objects, you cannot modify them internally.

It's like that VERY stubborn friend of yours.

It's always the same object, and their contents don't change πŸ˜‚

Ok, cool, but so what? πŸ€ͺ
When you call a function in Python, the model you use is β€œpass-by-assignment”.

This means that the parameters of the function just become new labels to the objects you gave as arguments.

How can we tell this..?
If you've been paying attention, you should know by now!

You can check that it's the same objects, just with a different label, because the identity of the objects is the same.

Here's a function that prints the identity of its only argument πŸ‘‡
As you could see, being (im)mutable didn't matter: when we call `foo`, β€œx” just becomes a new label to the exact same object we had _outside_ of the function.

So that means the following:
― if you give mutable objects to your function, your function can change the inner contents of your objects.

That's what sometimes trips people up.

The classical examples in Python 🐍 are lists and dictionaries.
Careful when using them inside your function πŸ‘‡
I think this is it for this thread πŸ˜‰ In < 24 hours I will publish a Pydon't on my blog (mathspp.com/blog/pydonts) with all this information, more examples, and also all the sources.

This way you'll be able to do some research on your own, as well.
If you like the way I explain these interesting Python 🐍 concepts, and you'd like more...

Make sure to follow me (@mathsppblog) to not miss a single drop of knowledge I share!

I would also love it if you could retweet the beginning of this thread πŸ’ͺπŸ”₯:

I hope that you found this thread very informative, and I'll gladly take any questions you might have πŸ‘‡πŸ’¬

Here's a TL;DR:

πŸ‘‰ python uses pass-by-assignment (not pass-by-value, not pass-by-reference);
πŸ‘‰ all objects have 3 different characteristics: an id, a type, contents;
πŸ‘‰ `is` checks if two names point to the same object;
πŸ‘‰ when calling functions, parameters become labels to the objects that were passed in;
πŸ‘‰ for mutable objects (that can have their contents changed), the function can make changes that are visible from the outside.

Bye πŸ‘‹

β€’ β€’ β€’

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

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
28 Sep
Interested in improving your Python 🐍 skills?

πŸ€” If you are, have you learned about conditional expressions?

Here is a MEGA thread πŸ‘‡πŸ§΅ teaching you almost everything there is to know about conditional expressions!

I will include a bunch of examples πŸ–Ό, so don't worry!
This is the follow-up to my experiment from earlier today.

I tried teaching you about conditional expressions without words 😢.

Here is the original thread:

Alright, so conditional expressions aren't that hard, really.

It is just an expression: a piece of code that evaluates to a result.

But then, it is tied to a condition: depending on whether the condition is truthy or falsy, the final result changes.

Check the function below:
Read 30 tweets
28 Sep
πŸ€” If you are learning Python 🐍, I want to do an experiment:

Here's a thread πŸ‘‡πŸ§΅ teaching you conditional expressions.

BUT, I will teach you with NO words 😢

I will only show code snippets and examples.

Check the thread out carefully πŸ” and then give me your feedback!
By the way, if you want to learn something from this thread...

I'm not going to lie, you'll have to focus πŸ”.

Also, what's the rationale for this crazy πŸ€ͺ thread?

By reading code and examples, you see first-hand how the feature is used and where it comes in handy.

Let's go:
Read 17 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!

:(