Python's comma equals ,= operator?

mCoding · Intermediate ·5y ago

Key Takeaways

Explains the usage of the comma equals operator ,= in Python for assignment expressions

Full Transcript

what's up everyone james murphy here from m coding back with another video on python weirdness do you know what the comma equals operator does in python if you know the answer to this trick question let me know down below in the comments otherwise here are some choices in this situation x is one y is the list containing two and we're looking at x comma equals y afterwards we're printing out the value of x so is x the integer one is x the integer two is x the singleton list containing one is x the tuple containing one and list of two or is this just a syntax error pause the video now if you need some time to think about it all right done thinking about it so do you know what the comma equals operator does let's find out by running it x gets the value 2. did you get it right well if you're like me then you probably thought this was just a syntax error when i first saw this in a real code base i thought it was a syntax error and maybe that i accidentally put the comma in myself well that's not true as you can see this does something so if you're not sure about why this printed out too let's look at a simpler example but first let me give you a hint i'll run my code formatter on it did you see what happened here let me do it again ready format it moved the comma do you know the answer now if not let's just go through it here is a simpler example suppose we have a function you know do something and x is 1 and y is 2 then we can say x comma y equals y comma x what this syntax does is it will swap the values of x and y it's kind of doing a little bit of pattern matching let me put in some unnecessary parentheses here it's kind of saying look at this pattern on the left x comma y and try to extract out values for x and y based off of what's on the right hand side where you see y comma x in this case it kind of makes sense that it would swap the values of x and y because i would say well matching the pattern x should be the thing inside the tuple which is at the zeroth index so that's y and y should be the thing which is inside the tuple at the first index which is x so afterwards x is equal to what y was and y is equal to what x was well this would work just as well if this was a list or any other iterable with two elements in it and here's where we see our previous example x comma equals y if you have a list of just one thing or a tuple of just one thing the syntax looks a little different so suppose x was like this a tuple of one thing in in python gives you the following syntax you need to have this extra trailing comma after the single element in the tuple because otherwise it just looks like you parenthesized x and we don't want parentheses to be creating tuples unless you really meant to so in this case if you want the left hand side to be a tuple you need to put that comma in but these parentheses are still optional so now do you see why x comma equals something gives you the value that it did before well our previous case looked like this y was 2 and we just said x comma equals y so now y here is just like we're putting two in so it's saying pattern match this tuple of one thing with this list of one thing that's why x gets the value two at the end of it make sense now is there any real case where you might want to use this syntax admittedly if you're using this syntax you might be in a gray area at the very least absolutely do not format it this way put the spaces in the right place otherwise you're just going to confuse people so i have come up with one case where it might actually you know makes sense to have something like this let's suppose that i have two sets and i know that their intersection has only one element so just for demonstration purposes let's say that we have a list of primes you know 2 3 5 7 11. and we have a list of evens which is 2 4 6 8 10. let me actually make these sets not lists now i know that the set of evens and the set of primes only has one thing in common and that's two so i could say x comma equals with the correct spacing of course primes dot intersect intersection with the evens and then print x so in this case if i call do something now we see that again it prints out two so that's one case where if you know ahead of time that there's only one thing in the right hand side then you might actually want to use this comma equal syntax instead of having a temporary variable you know intersection equals this and then x equals intersection dot pop to get the one element out there you have it that's the comma equals operator in python hey thanks for watching again if you like the video remember to like comment and subscribe also i offer online python courses so if you would like to learn python from me then go ahead and drop your contact info at the link in the description and i'll let you know when online python courses are available

Original Description

Do you know what x ,= y does in Python? ― mCoding with James Murphy (https://mcoding.io) Source code: https://github.com/mCodingLLC/VideosSampleCode SUPPORT ME ⭐ --------------------------------------------------- Patreon: https://patreon.com/mCoding Paypal: https://www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJHEE Other donations: https://mcoding.io/donate BE ACTIVE IN MY COMMUNITY 😄 --------------------------------------------------- Discord: https://discord.gg/Ye9yJtZQuN Github: https://github.com/mCodingLLC/ Reddit: https://www.reddit.com/r/mCoding/ Facebook: https://www.facebook.com/james.mcoding
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from mCoding · mCoding · 2 of 60

1 Goodbye, List! Type hinting standard collections - New in Python 3.9
Goodbye, List! Type hinting standard collections - New in Python 3.9
mCoding
Python's comma equals ,= operator?
Python's comma equals ,= operator?
mCoding
3 Finding Primes in Python with the Sieve of Eratosthenes
Finding Primes in Python with the Sieve of Eratosthenes
mCoding
4 Find the First Missing Positive Int | Hard Interview Question on LeetCode
Find the First Missing Positive Int | Hard Interview Question on LeetCode
mCoding
5 JSON Tutorial Python | Basic Python Recipes
JSON Tutorial Python | Basic Python Recipes
mCoding
6 Simulating Brownian Motion in Python
Simulating Brownian Motion in Python
mCoding
7 The Single Most Useful Decorator in Python
The Single Most Useful Decorator in Python
mCoding
8 The Fastest Way to Loop in Python - An Unfortunate Truth
The Fastest Way to Loop in Python - An Unfortunate Truth
mCoding
9 Numpy Array Broadcasting In Python Explained
Numpy Array Broadcasting In Python Explained
mCoding
10 Brownian Motion Single Path Zoom
Brownian Motion Single Path Zoom
mCoding
11 Brownian Motion Fractal Zoom
Brownian Motion Fractal Zoom
mCoding
12 Magic Methods - Making Python builtins work with your classes
Magic Methods - Making Python builtins work with your classes
mCoding
13 50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
mCoding
14 The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
mCoding
15 How Fast is Python's Sort? Performance Testing
How Fast is Python's Sort? Performance Testing
mCoding
16 C++ First Missing Int, faster than 100%!
C++ First Missing Int, faster than 100%!
mCoding
17 [April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
[April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
mCoding
18 Python dataclasses will save you HOURS, also featuring attrs
Python dataclasses will save you HOURS, also featuring attrs
mCoding
19 C++ Sudoku Solver in 7 minutes using Recursive Backtracking
C++ Sudoku Solver in 7 minutes using Recursive Backtracking
mCoding
20 Every PROOF you've seen that .999... = 1 is WRONG
Every PROOF you've seen that .999... = 1 is WRONG
mCoding
21 Python's sharpest corner is ... plus equals? (+=)
Python's sharpest corner is ... plus equals? (+=)
mCoding
22 Binary Search - A Different Perspective | Python Algorithms
Binary Search - A Different Perspective | Python Algorithms
mCoding
23 The Best Way to Check for Optional Arguments in Python
The Best Way to Check for Optional Arguments in Python
mCoding
24 Local and Global Variable Lookup Weirdness in Python
Local and Global Variable Lookup Weirdness in Python
mCoding
25 Efficient Exponentiation
Efficient Exponentiation
mCoding
26 How To Install Python for Data Science
How To Install Python for Data Science
mCoding
27 0.1 + 0.2 is NOT 0.3 in Most Programming Languages
0.1 + 0.2 is NOT 0.3 in Most Programming Languages
mCoding
28 Python 3.10's new type hinting features
Python 3.10's new type hinting features
mCoding
29 Python 3.10's Quality of Life improvements
Python 3.10's Quality of Life improvements
mCoding
30 Introducing mZips! Python Zip and Zip Longest
Introducing mZips! Python Zip and Zip Longest
mCoding
31 Match statement tips
Match statement tips
mCoding
32 Using except: is a HUGE mistake
Using except: is a HUGE mistake
mCoding
33 Python + YouTube API | Automating descriptions
Python + YouTube API | Automating descriptions
mCoding
34 Anaphones, phonetic anagrams
Anaphones, phonetic anagrams
mCoding
35 Cracking passwords using ONLY response times | Secure Python
Cracking passwords using ONLY response times | Secure Python
mCoding
36 Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
mCoding
37 Diagnose slow Python code. (Feat. async/await)
Diagnose slow Python code. (Feat. async/await)
mCoding
38 Python MD5 implementation
Python MD5 implementation
mCoding
39 Salting, peppering, and hashing passwords
Salting, peppering, and hashing passwords
mCoding
40 x to bool conversion in Python, C++, and C
x to bool conversion in Python, C++, and C
mCoding
41 You should put this in all your Python scripts | if __name__ == '__main__': ...
You should put this in all your Python scripts | if __name__ == '__main__': ...
mCoding
42 Find the Skyline Problem with C++ Solution Explained
Find the Skyline Problem with C++ Solution Explained
mCoding
43 The ONLY C keyword with no C++ equivalent
The ONLY C keyword with no C++ equivalent
mCoding
44 Should you use "not not x" instead of "bool(x)" in Python? (NO!)
Should you use "not not x" instead of "bool(x)" in Python? (NO!)
mCoding
45 Multiple Assignments in Python
Multiple Assignments in Python
mCoding
46 Why I don't like Python's chained comparisons
Why I don't like Python's chained comparisons
mCoding
47 Automated Testing in Python with pytest, tox, and GitHub Actions
Automated Testing in Python with pytest, tox, and GitHub Actions
mCoding
48 You can pip install directly from GitHub
You can pip install directly from GitHub
mCoding
49 __new__ vs __init__ in Python
__new__ vs __init__ in Python
mCoding
50 Metaclasses in Python
Metaclasses in Python
mCoding
51 The easy way to keep your repos tidy.
The easy way to keep your repos tidy.
mCoding
52 Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
mCoding
53 Python __slots__ and object layout explained
Python __slots__ and object layout explained
mCoding
54 C++ cache locality and branch predictability
C++ cache locality and branch predictability
mCoding
55 Avoiding import loops in Python
Avoiding import loops in Python
mCoding
56 25 nooby Python habits you need to ditch
25 nooby Python habits you need to ditch
mCoding
57 Python staticmethod and classmethod
Python staticmethod and classmethod
mCoding
58 Building a Python app with Anvil to email me if my website goes down (includes paid features)
Building a Python app with Anvil to email me if my website goes down (includes paid features)
mCoding
59 31 nooby C++ habits you need to ditch
31 nooby C++ habits you need to ditch
mCoding
60 Interviewing the creator of C++, Bjarne Stroustrup
Interviewing the creator of C++, Bjarne Stroustrup
mCoding
Up next
George Hotz | Programming | tinygrad, starting on CLOUD=1 | Part 2
george hotz archive
Watch →