Is THIS Python's MOST Underrated Operator? (Walrus Operator)

  Рет қаралды 33,552

Indently

Indently

Күн бұрын

Is this Python's most underrated operator? Today we're going to be learning how we can use the Walrus Operator which was introduced in Python 3.8. I personally love it and use it all the time, what about you?
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels
00:00 Intro
00:13 What is the Walrus Operator?
00:50 Example 1
03:10 Example 2
04:21 Example 3
05:21 Summing it up

Пікірлер: 107
@SuperVirus1978
@SuperVirus1978 Жыл бұрын
I absolutely dislike the first use-case shown, because it "hides" the assignments within other pieces of code. IMHO it makes the code less readable - especially without an IDE these assignments are sometimes hard to spot. In contrast I like the use of the walrus operator within the if-statement. Here is a clear connection where the variable is assigned becaue it is ususally only used in the branches of the if-statement.
@Indently
@Indently Жыл бұрын
I enjoy using it for short lines of code in dictionaries. I mean if you convolute it, of course it might become less readable. But the same thing goes for list comprehensions in the end. For now I suffered no readability problems with the first approach, but I will have to update you in 6 months when I look back at it. If I can read it without any comments, I'll know for sure 😅
@Indently
@Indently Жыл бұрын
The thing is: it's sugar syntax.
@DrDeuteron
@DrDeuteron Жыл бұрын
I agree. I remember reading there is no n++ operator b/c Guido never mixes expressions and assignments, but I guess that is passé. Moreover, which order is the dict construction evaluated? I guess left to right, but that is non-pythonic code imho. Also: what if you assign to word more than once in the dict constructor? Sounds buggy af.
@davea136
@davea136 26 күн бұрын
People used to look at my Perl code and instantly say, "You're a C programmer, aren't you?" YES! Because I like very easy to read code. I like declaring everything clearly. I like for each statement to clearly ahve a purpose. I prefer to not obfuscate the code with incidental assignments or side-effects or "cool tricks" of any kind. Sure, I use extra lines. Here's a secret: The compiler does not care. Here's another reason to not use the walrus operator - if you are that 1 in 1000 python eveloper that actually uses the debugger *gasp* instead of prints everywhere it makes things harder to debug.
@Kommentierer
@Kommentierer Жыл бұрын
I want to use the walrus now.
@vikingthedude
@vikingthedude 11 ай бұрын
I am the walrus
@philkeier2652
@philkeier2652 8 ай бұрын
Now your Codes looks like scrambled JavaScript.
@theViceth
@theViceth 9 ай бұрын
My personal favourite is the while loop. While it still isn't a proper do-while, i can at least replace the standard true check and discard the unnecessary if breaks.
@Talent_Unlimited
@Talent_Unlimited Жыл бұрын
That's so helpful! Thank you!
@user-yk5nu4kr3q
@user-yk5nu4kr3q Жыл бұрын
I enjoy utilizing this functionality within if statements when working with complex JSON data. It is particularly useful when I want to modify the value associated with a specific key, but I'm uncertain if the key exists in every record. Here's an example: if value := my_dict.get("key"): # Perform certain operations using the value my_dict["key"] = new_value
@starmscloud
@starmscloud Жыл бұрын
Excellent.. learned something new today !.. Thank You !
@pallenda
@pallenda Жыл бұрын
Cool video! For some reason it confused me a bit with 'words' and words := Took me a bit to understand that the words variable and 'words' wasn't referring to the same thing. details: dict = {'all_the_words' : (words := text.split())}, That version might have made it easier for me. 😅
@ChrisHalden007
@ChrisHalden007 4 ай бұрын
Great video. Thanks
@il_dimas7337
@il_dimas7337 Жыл бұрын
Found out about warlus oprator in one of the leetcode solutions. Glad to see info about it in KZfaq video
@maxca
@maxca Жыл бұрын
Woow ive heard about walrus operator before but never knew how to use it. Thanks!
@xanderlewis
@xanderlewis 7 ай бұрын
'Walrus Operator' is going to be my new band name.
@gksculpture
@gksculpture 3 ай бұрын
Love this 👍🏾
@Sailesh_Bhoite
@Sailesh_Bhoite 4 ай бұрын
Nice tricks!
@datboi_gee
@datboi_gee 4 ай бұрын
been using walrus operator left and right ever since it was added, really such a beautiful tool to condense code while making things even more self-documented. I wonder if it's possible, however, to add your own custom operators into python. Like a +> for the equivalent of a self-inclusive max() function. max_sum +> sum(vals) vs max_sum = max(max_sum, sum(vals) where the evaluation is baked into the operator, and the value for use in the comparison is implied much like a += operator.
@ItzPouriya
@ItzPouriya Жыл бұрын
So good explains! how do u use emojis in ur strings??
@jamesmiller5984
@jamesmiller5984 Жыл бұрын
I learned about the walrus two days ago it definitely an interesting one.
@junioralves9526
@junioralves9526 11 ай бұрын
I wish i already have knew about that operator when i made python algorithms avaliations on paper. It will certainly save me when i forgot to declare variables on the first lines😂😂
@fromgermany271
@fromgermany271 Жыл бұрын
So what‘s complained about in C(++) for decades is now honored for keystroke saving in other languages as well 😂
@namvu607
@namvu607 Жыл бұрын
New and come in handy 🤩
@naturfagstoff
@naturfagstoff Жыл бұрын
Powerful operator, but I feel a bit discouraged by the complexity in the operation still. Seems to me it will take some time getting used to.
@michaelemulu
@michaelemulu Жыл бұрын
you have to adopt changes Else: you'll be left behind
@joseoncrack
@joseoncrack 9 ай бұрын
Just think of all the new operators you'll have in Python 10.0!
@KeithKazamaFlick
@KeithKazamaFlick 8 ай бұрын
@@joseoncrack if im still alive yeh lol
@joseoncrack
@joseoncrack 8 ай бұрын
@@KeithKazamaFlick Get ready for the double-Walrus operator: =:= (no it won't be a cat smiley, but an operator). This one will allow bidirectional assignment. Yes, this is groundbreaking. Don't thank me.
@RobertLugg
@RobertLugg 8 ай бұрын
Python was originally written to not not have all these handy but complex feature like previous languages. After 30 years people realize the value of those "old" constructs and are adding them back.
@bassycounter
@bassycounter 11 ай бұрын
I’m slightly confused but I’m determined to understand it cause it does seem really handy for cleaning up code
@rasmuskaj
@rasmuskaj 9 ай бұрын
The use in the if statement is great, but my favorite is the use in elif, where it saves not only a line of code or two, but actually an indention level!
@kareltavernier6642
@kareltavernier6642 2 ай бұрын
This is a really good point.
@viktoreidrien7110
@viktoreidrien7110 Жыл бұрын
nice !!
@houstonbova3136
@houstonbova3136 11 ай бұрын
Literally use it all the time. Super useful for conditional filtering. Here’s a sample where I assign the data from a mutex and then assign it again to the filtered subset to prevent an empty data frame from being returned if you accidentally configured out all of your data. def filter_data(selected_rows): if len(dff := (df := get_data()).iloc[selected_rows]) == 0: return df return dff
@athulkrishnadiyil1735
@athulkrishnadiyil1735 9 ай бұрын
i got an instant rejection in an interview for not having good knowledge about this so called Walrus operator.
@epicanthus
@epicanthus Жыл бұрын
I wouldn’t use the walrus operator in a dictionary. However, I think the most useful usecase of the walrus operator is not mentioned in the video. I usually use it to assign a value to a variable and do something if its new value differs from its previous. I use this approach when I want to update a tkinter widget only and only if its parameters have changed. if x != (x := func()): # order matters! do_things() Without the walrus operator I would have to use a temporary variable, like: previous_value = x x = func() if previous_value != x: do_things()
@LiamInviteMelonTeee
@LiamInviteMelonTeee Жыл бұрын
Oh damn that's a cool one
@DrDeuteron
@DrDeuteron Жыл бұрын
you should pass x to do_things()....just to show that you actually need it.
@epicanthus
@epicanthus Жыл бұрын
Not necessarily. You may use x only next time your program reaches this snippet to check whether x has been changed since last call.
@DrDeuteron
@DrDeuteron Жыл бұрын
@@epicanthus idk. I make all function pure, so this use case I would avoid. Maybe in a method.
@Bl0xxy
@Bl0xxy 2 ай бұрын
I use the walrus all the time with input() uses in if statements
@berni_schmorg
@berni_schmorg Жыл бұрын
Hey! I just tried using the operator in print(f'{absolute := abs(a - b)}') but that doesn't seem to work... is that not a use case for the walrus operator?
@berni_schmorg
@berni_schmorg Жыл бұрын
OHH wait it does work! It needs extra parentheses for some reason: print(f'{(absolute := abs(a - b))}')
@brijeshvarsani9972
@brijeshvarsani9972 Жыл бұрын
How to change the appearance of the arrow used for function annotations from "->" to a unicode arrow symbol?
@Indently
@Indently Жыл бұрын
You need to search for something called "Ligatures"
@hiredfiredtired
@hiredfiredtired Жыл бұрын
@@Indently Isn't that the thing you put on instruments to keep the reed on?
@user-vp3vs6ey3r
@user-vp3vs6ey3r 4 ай бұрын
@@hiredfiredtired Not in the crime documentaries that I've watched LOL
@julienblanchon6082
@julienblanchon6082 11 ай бұрын
Very usefull to iterate a tqdm iterator and still have access to the pbar object: for x in (pbar := tqdm(it)): ... pbar.set_postfix(...)
@leightaylor8069
@leightaylor8069 Жыл бұрын
Good video. The feature of Python I see underused a lot is the "dict.setdefault" method.
@Indently
@Indently Жыл бұрын
That's actually my next video coincidentally
@DrDeuteron
@DrDeuteron Жыл бұрын
I prefer collections.defaultdict, which is different...but usually more appropriate. just won't throw a KeyError.
@josgibbons6777
@josgibbons6777 11 ай бұрын
I can't believe you didn't mention while loops.
@MarcoAntoniotti
@MarcoAntoniotti 6 ай бұрын
Ok. It took about 30 years to get this in Python.
@eugenewii
@eugenewii Жыл бұрын
I thought I was the walrus, but maybe I'm the egg man.
@nbme5804
@nbme5804 Жыл бұрын
Koo Koo kachoo!
@EW-mb1ih
@EW-mb1ih 24 күн бұрын
Does this operator give any gain in speed performance ?
@michaelemulu
@michaelemulu Жыл бұрын
I learned sth. Thank you
@ShubhamChavan
@ShubhamChavan Жыл бұрын
I've been learning Python for a couple months now and this is the first time i Saw an arrow. damn this really discourages me and makes me feel dumb. But on the positive side there's so much more to learn and make my code more efficient. :D
@DrDeuteron
@DrDeuteron Жыл бұрын
and I have been doing py since 2002, and the arrow is new to me. As far as Im concerned it's for babies addicted to their IDEs to tell them how to write code. I mean I usually go with new python stuff, but this seems down right unpythonic. Java dev hand holding.
@IManu96I
@IManu96I Жыл бұрын
​@@DrDeuteronare you talking about the "->" in the function signature?
@DrDeuteron
@DrDeuteron Жыл бұрын
@@IManu96I the whole package. I mean when I see: name: str = "Monty" that is not pythonic at all.
@IManu96I
@IManu96I Жыл бұрын
@@DrDeuteron There is not any package imported in the line you wrote. Do you mean the use of "typing" package and type hints? What you wrote is redundant, the "str" has no effect there in that specific case. It is assumed that this is a str. And what do you mean with "no pythonic"? Its zen says "better explicit than implicit". Technically adding str is more explicit. In addition, the typing provides 1) extra IDE autocompletion (as the IDE knows the type of the variable), 2) new way of documenting code and 3) tools that can scan your code to verify that there is not anything breaking through static type checking, which is a way of static testing. When developing code for companies, it is a must. Many of them enforce it. It gives you confidence that your code will not break when running it or after a big refactor
@Pawlo370
@Pawlo370 22 күн бұрын
okay now i'm understand
@gardnmi
@gardnmi Жыл бұрын
The operator that made Guido quit python.
@DrDeuteron
@DrDeuteron Жыл бұрын
well that explains it.
@xzex2609
@xzex2609 Жыл бұрын
one of the best use case of walrus operator is to reduce the load of a function call , consider if you have such condition if ((f(x) > m > 2*f(x)) or (c >= f(x)) and (f(x)
@Bl0xxy
@Bl0xxy 2 ай бұрын
except i'd recommend not naming it f since your function is already named f :D
@jello195
@jello195 9 ай бұрын
why do yo declare variable as variable_name : type = x instead of variable_name = x ?
@cgyh68748
@cgyh68748 Жыл бұрын
How have I never seen this in a coding video before?
@istvandarvas3372
@istvandarvas3372 11 ай бұрын
saving one line of code means you are going to degarade the code readability --- so it is interesting, but I think it should nit be used a alot or abused i would say
@tihon4979
@tihon4979 4 ай бұрын
PEP 20: Explicit is better than implicit....
@gustavomaia2252
@gustavomaia2252 Жыл бұрын
How did he put a thumbs up in a string? 😂😂
@jackytaly
@jackytaly Жыл бұрын
I think it’s an overused operator, as in it should almost never be used. The only thing it does it make code less readable. Edit: To clarify, don’t use the operator unless you have a specific reason. If you use it just to save a line, it will likely cause headaches in debugging. especially in larger projects.
@Indently
@Indently Жыл бұрын
Out of curiousity, where do you see it overused? In 2 years I've seen it (only barely) a couple of times being used.
@jackytaly
@jackytaly Жыл бұрын
@@Indently I was being a little hyperbolic. By overused, I mean using it even once is too much. I just personally don’t like it because in every use case I can think of it reduces readability for the sake of saving one additional line. Edit: Fyi it wasn’t meant to be a dig, I do enjoy your channel. Just wanted to share my opinion, as at the time I saw many comments from beginners that wanted to try using this operator.
@DrDeuteron
@DrDeuteron Жыл бұрын
I agree. I use it in if statements where I need the value on some branches but not all..esp if I only need it to throw errors with messages. I mean if I need the value for clean execution, I'm happy to devote a line of code.
@rishiraj2548
@rishiraj2548 Жыл бұрын
🙏👍
@Rainmakeroffire
@Rainmakeroffire Жыл бұрын
4:15 - can't get this one. What prevents you from putting it as simple as that: user_input = 'Hello world' if len(user_input) > 5: print(user_input, '👍') else: print(user_input, '👎') Why would you even need the 'text' variable?
@gregoriopescucci4997
@gregoriopescucci4997 Жыл бұрын
Because in the example text is the length of the string, not the string itself (that's user_input), so in the output you would need to rewrite print(len(user_input), "emoji"). Just a poorly named variable, should've been called something like "string_length".
@Rainmakeroffire
@Rainmakeroffire Жыл бұрын
@@gregoriopescucci4997 oh yeah, I've just realized it was the string length. Still I don't think it's worth the trouble to create a separate variable, just to avoid mentioning len() twice.
@DrDeuteron
@DrDeuteron Жыл бұрын
I reject 2 function calls, and would do: print(user_input, 'up' if Len(user_input) > 5 else 'down') no, I would have:\ RESPONSE = {True: 'up', False: 'down'} defined in the appropriate namespace and have 1 execution line: print(ui, RESPONSE[len(ui) > 5]) because I prefer static complexity over dynamic complexity...within reason.
@elmussom5433
@elmussom5433 Жыл бұрын
Im suprised nobody invented this earlier. I needed this operator for many years
@AlexCernat
@AlexCernat Жыл бұрын
welcome python to 21st century 😀 nothing new that man can do in c, perl, php etc. since eons ago!
@michaelraasch5496
@michaelraasch5496 Жыл бұрын
Doing everything in one line is meant for PERL :-)
@Lucs-ku5cb
@Lucs-ku5cb Жыл бұрын
Or Haskell
@TSPxEclipse
@TSPxEclipse 27 күн бұрын
Ok, I'm sorry but I burst into laughter seeing you copy-paste in the thumbs-up and thumbs-down emojis. Emojis in code are so cursed.
@RoboArc
@RoboArc Жыл бұрын
It's still 2 lines. Not any faster doing this btw. Makes your library less new user freindly too. Since not everyone uses them regularly. Almost no reason for all this The if statement is useful though. Didn't like the first example much.
@user-vt9bp2ei1w
@user-vt9bp2ei1w Жыл бұрын
As far as I personally use it, the whole purpose of Walrus Operator is actually to reduce some annoying template typing. For example, when you use coroutines (implemented by generators), you always have to type over and over again like x=getCoro(); next(x); y=getCoro(); next(y) Or when performing regular matching, m=re.match(...); if m is not None: return ...; m=re.match(...); if m is not None: return . ..; these templates are really intrusive and interfere with readability. The Walrus Operator helps with readability as long as you maintain consistency throughout your source code.
@HoSza1
@HoSza1 Жыл бұрын
Instead of the following value = produce() while value is not None: consume(value) value = produce() You can write this: while (value := produce()) is not None: consume(value)
@DrDeuteron
@DrDeuteron Жыл бұрын
that is nice
@Yupppi
@Yupppi 7 ай бұрын
print( ( 👎, 👍) [len(user_input) > 5] ) I never get to use ternary operator in programs I write.
@Indently
@Indently 7 ай бұрын
But the ternary operator isn’t the walrus operator, unless you’re just talking about the ternary operator with no correlation to the video.
@mikesmith6838
@mikesmith6838 5 ай бұрын
Oh great, another operation, like list comprehension, that will allows programmers to write even more unreadable code. Well done, Python.
@Indently
@Indently 5 ай бұрын
You’re every marketing teams worst nightmare for a business 🤣
@KeithKazamaFlick
@KeithKazamaFlick 8 ай бұрын
:=
@NathanChambers
@NathanChambers 11 ай бұрын
It really is useless for most cases, since most python projects are small. If all python projects were huge, than yes this would be underrated. But as it stands, it's OVERrated in "every day" small python scripts.
@aliasgar.burhani1099
@aliasgar.burhani1099 Жыл бұрын
I thought Go was the one to introduce walrus operator ... but python did it before
@quillaja
@quillaja 2 ай бұрын
:= was used for assignment in Pascal. Maybe others.
@DrDeuteron
@DrDeuteron Жыл бұрын
I don't think I like type hints.
@sh1maru
@sh1maru Жыл бұрын
This operator literally killed python
@Indently
@Indently Жыл бұрын
Yeah, Python was never used again by anyone after this sugar syntax
@davea136
@davea136 26 күн бұрын
OMG! Use a WHOLE OTHER LINE?!?! Seriously, people. If screen space is the issue let's just go back to Perl so we can mystify people with one-liners in the O.G. way. Your eyes travel to the left to see declarations of vars. Embedding it in the center of a line disrupts that. Boo!
@valorien1
@valorien1 4 ай бұрын
You completely "skipped" over what the operator does and what it actually means and just jumped straight over to an example. Seems like you missed the entire point of the video you yourself created. What a shame, and a waste of time.
@Indently
@Indently 4 ай бұрын
Hey there! If you consider the video a waste of time, imagine how others will see your comment. I'm sorry you saw it as a waste of time, maybe you'd like to share a better example so more people can learn from your comment? I mean, the real shame is not being constructive in the comments section to help people :)
@user-vp3vs6ey3r
@user-vp3vs6ey3r 4 ай бұрын
@@Indently I've always felt that the best way to explain 'abstract' concepts like the walrus was through the use of examples.
Python's 5 Worst Features
19:44
Indently
Рет қаралды 104 М.
路飞被小孩吓到了#海贼王#路飞
00:41
路飞与唐舞桐
Рет қаралды 82 МЛН
Пранк пошел не по плану…🥲
00:59
Саша Квашеная
Рет қаралды 6 МЛН
Python 3.12 is HERE!
12:37
mCoding
Рет қаралды 157 М.
5 Really Cool Python Functions
19:58
Indently
Рет қаралды 57 М.
The Python Walrus Operator is Awesome!
13:41
k0nze
Рет қаралды 703
5 Tips To Write Better Python Functions
15:59
Indently
Рет қаралды 98 М.
5 More Useful F-String Tricks In Python
9:38
Indently
Рет қаралды 45 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 453 М.
What is a Monad? - Computerphile
21:50
Computerphile
Рет қаралды 597 М.
The Flaws of Inheritance
10:01
CodeAesthetic
Рет қаралды 917 М.
路飞被小孩吓到了#海贼王#路飞
00:41
路飞与唐舞桐
Рет қаралды 82 МЛН