What's "assignment" in #Python?

This might seem like a simple concept, but there are some gotchas in the way assignment works in Python.

Fundamentally "assignment" describes the action of binding a name to a value.
You can assign a variable (a.k.a. name) to a value (a.k.a. object) with an "assignment statement".

That uses an = sign, like this:

>>> x = []

That assigns the name x to an empty list.

If "x" already exists, an = sign will re-assign it to a new value:

.>>> x = 4
>>> x
4
Python programmers often talk about names "binding" to objects or variables "pointing" to objects.

In Python, variables point to (or "refer to") values. Variables don't *contain* objects, but just say "look over there for the object". 👀

Beware of code like this:

x = []
y = x
Why beware? Well, two variables can point to the same object.

The second line here points "y" to the same object that "x" is pointing to:

>>> x = []
>>> y = x

Mutating the object will appear to change both variables:

>>> y.append(4)
>>> x
[4]

😦
The distinction between mutation and assignment is important in Python.

Assignment changes which object a variable points to.

Mutation changes the object itself.

And function calls assign (without copying), which can confuse as well.

More on this 👇

pym.dev/pointers
That's not the only surprise when it comes to assignment in Python though.

When we talk about assigning variables and assignments, we're often referring to assignment statements (a line with an = sign on it).

But that's not the only way to assign a variable in Python! 😕
For loops also assign to variables in each iteration of their loop.

Watch "x" get reassigned here:

>>> x = 0
>>> for x in range(3):
... print(x)
...
0
1
2
>>> x
2

The last iteration of the loop assigned it to 2!

There are assignments hiding all over...
Function definitions assign a variable (the function name) to a new function object:

>>> x
2
>>> def x(): pass
...
>>> x
<function x at 0x7fbb8a10a560>

Class definitions assign variables to a new class object:

>>> class x: pass
...
>>> x
<class '__main__.x'>
Even import statements perform assignments.

>>> import json
>>> json
<module 'json' from '/usr/lib/python3.11/json/__init__.py'>

The "from" syntax performs many assignments:

>>> from math import e, tau
>>> e
2.718281828459045
>>> tau
6.283185307179586
Another surprise: assignment statements can sometimes mutate! 🤔

Specifically, augmented assignment statements (a.k.a. in-place assignments) such as += and *= will typically mutate the object being assigned if it's mutable.

>>> x = y = []
>>> x += [1, 2]
>>> y
[1, 2]
One more big fact about assignment in Python:

Assignment changes LOCAL variables only*

>>> x = 0
>>> def f():
... x = 4
...
>>> f()
>>> x
0

If there's a global variable of the same name, it will be "shadowed" but left unchanged.

pym.dev/local-and-glob…
Pedants may say "but wait, you CAN assign to global and nonlocal variables in Python by using special statements".

That's right, but you usually shouldn't. It's rarely a good idea and often an indication that your code could benefit from well-placed return statements or a class.
I'll leave a bigger discussion of namespaces and scope for another day... but I'd like to close this thread by linking to over a dozen screencasts on @PythonMorsels on assignment, mutation, and scope.

1. pym.dev/screencasts/va…
2. pym.dev/screencasts/as…

Many are free 💓🐍
I forgot the #TerminologyTuesday hashtag! 😮

Still wishing for a an "edit" button on Twitter 😅

• • •

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

Keep Current with Trey Hunner (Python trainer)

Trey Hunner (Python trainer) 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 @treyhunner

Aug 29
Python's strings have 47 methods!

But these 12 string methods are the only ones really worth committing to memory for most Python programmers:

join
split
replace
strip
casefold
startswith
endswith
splitlines
format
count
removeprefix
removesuffix A table showing the 12 stri...
But what about find, encode, translate, isnumeric, and all the other string methods?

While there are other useful string methods, most of the remaining methods have a niche use case or have quirks that make them tricky to use.

For example the title method has quirks 👇
And methods like isnumeric, isdigit, and isdecimal unfortunately take a bit of studying to figure out, so I recommend either avoiding them or using them carefully.
Read 5 tweets
Aug 23
What's a "generator" in Python?

#TerminologyTuesday time ⏰

Let's discuss:
• The main reason generators are used
• The 2 ways to make a generator
• Lesser known generator features
• Why and when to use generators

Thread 🧵👇
Generators are typically used as lazy iterables.

By "lazy" I mean that they don't actually compute their values until they absolutely need to.

Essentially generators will "generate" their next value as soon as they're asked for it.
Here's a generator of every .py file in my home directory:

>>> from pathlib import Path
>>> py_files = Path.home().rglob("*.py")
>>> py_files
<generator object Path.rglob at 0x7f5a6721c900>

(the rglob method on pathlib.Path objects always returns a generator)
Read 21 tweets
Aug 9
What's a regular expression (a.k.a. regex)? 🤔 #TerminologyTuesday

Yes, they're a programming language within a programming language that's just for pattern matching and they're extremely succinct.

But what does "regular expression" really mean? And where did they come from?
Haven't seen regular expressions?

Imagine a special purpose programming language where every single character is a statement and no whitespace or comments are allowed. 😨

Regular expressions are extremely information dense but very helpful for certain types of pattern matching.
Regular expressions are called "regular" because regular expressions define a "regular language".

What's a "regular language"?

I'm so glad you asked! This is one of the few factoids from my CS degree that actually stuck with me.

This part of CS is tightly tied to linguistics.
Read 17 tweets
Aug 3
I usually recommend the "literal" list & dict syntax in #Python over the built-in list & dict functions.

✅ []
🚫 list()

✅ {}
🚫 dict()

✅ {"name": "Trey", "id": 4}
🚫 dict(name='Trey', id=4)

So what's the purpose of list(...) and dict(...)? 🤔

Copying!

(thread🧵)
Per the Zen of Python:

> there should be one— and preferably only one —obvious way to do it

I see [] and {} as "the one obvious" way to make a new list/dict.

[] and {} are even more common than list() and dict() so are likely more obvious to most Python devs.
What about passing keyword arguments to dict(...)?

This is a neat trick, but its use is limited.

Using non-string or invalid Python variables as keys doesn't work:

>>> d = dict(class="yes")
SyntaxError: invalid syntax

I don't find the benefits of dict(...) worth 2 syntaxes.
Read 8 tweets
Aug 2
What's an "object" in Python?

According to the Python glossary, an object is:

> Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any new-style class.

What does that really mean? (thread🧵)

#Python #TerminologyTuesday
Usually when we think of an "object" we think of class instance. For example these are all objects:

>>> numbers = [2, 1, 3, 4, 7] # a list object
>>> colors = {"red", "green", "blue", "yellow"} # a set object
>>> name = "Trey" # a string object
>>> n = 3 # an int object
Anything that can have attributes is an object.

Anything that can has methods is an object.

Anything that you can point a variable to is an object.

Pretty much EVERY THING is an object in Python.
Read 8 tweets
Aug 1
Need to remove all spaces from a string in #Python? 🌌🐍

Let's take a quick look at:

• removing just space characters
• removing all whitespace
• collapsing consecutive whitespace to 1 space
• removing from the beginning/end
• removing from the ends of every line

Thread🧵
If you just need to remove space characters you could use the string replace method to replace all spaces by an empty string:

>>> greeting = " Hello world! "
>>> greeting.replace(" ", "")
'Helloworld!'

But you may also want to remove other whitespace too (e.g. newlines)...
To remove all sorts of whitespace, you could use the string split method along with the string join method:

>>> version = "\tpy 310\n"
>>> "".join(version.split())
'py310'

Or you could use a regular expression:

>>> import re
>>> re.sub(r"\s+", "", version)
'py310'
Read 8 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

Don't want to be a Premium member but still want to support us?

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

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us on Twitter!

:(