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

แชร์
ฝัง
  • เผยแพร่เมื่อ 30 ก.ค. 2024
  • 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 ปีที่แล้ว +84

    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  ปีที่แล้ว +1

      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  ปีที่แล้ว +3

      The thing is: it's sugar syntax.

    • @DrDeuteron
      @DrDeuteron ปีที่แล้ว +4

      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 29 วันที่ผ่านมา +1

      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 ปีที่แล้ว +34

    I want to use the walrus now.

    • @vikingthedude
      @vikingthedude 11 หลายเดือนก่อน

      I am the walrus

  • @philkeier2652
    @philkeier2652 8 หลายเดือนก่อน +6

    Now your Codes looks like scrambled JavaScript.

  • @Talent_Unlimited
    @Talent_Unlimited ปีที่แล้ว +1

    That's so helpful! Thank you!

  • @starmscloud
    @starmscloud ปีที่แล้ว

    Excellent.. learned something new today !.. Thank You !

  • @user-yk5nu4kr3q
    @user-yk5nu4kr3q ปีที่แล้ว +5

    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

  • @il_dimas7337
    @il_dimas7337 ปีที่แล้ว

    Found out about warlus oprator in one of the leetcode solutions. Glad to see info about it in TH-cam video

  • @theViceth
    @theViceth 9 หลายเดือนก่อน +5

    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.

  • @pallenda
    @pallenda ปีที่แล้ว +7

    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. 😅

  • @maxca
    @maxca ปีที่แล้ว

    Woow ive heard about walrus operator before but never knew how to use it. Thanks!

  • @ChrisHalden007
    @ChrisHalden007 4 หลายเดือนก่อน

    Great video. Thanks

  • @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.

  • @gksculpture
    @gksculpture 3 หลายเดือนก่อน

    Love this 👍🏾

  • @ItzPouriya
    @ItzPouriya ปีที่แล้ว

    So good explains! how do u use emojis in ur strings??

  • @Sailesh_Bhoite
    @Sailesh_Bhoite 4 หลายเดือนก่อน

    Nice tricks!

  • @jamesmiller5984
    @jamesmiller5984 ปีที่แล้ว

    I learned about the walrus two days ago it definitely an interesting one.

  • @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!

  • @xanderlewis
    @xanderlewis 7 หลายเดือนก่อน +1

    'Walrus Operator' is going to be my new band name.

  • @bassycounter
    @bassycounter 11 หลายเดือนก่อน +1

    I’m slightly confused but I’m determined to understand it cause it does seem really handy for cleaning up code

  • @junioralves9526
    @junioralves9526 ปีที่แล้ว +1

    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😂😂

  • @namvu607
    @namvu607 ปีที่แล้ว

    New and come in handy 🤩

  • @viktoreidrien7110
    @viktoreidrien7110 ปีที่แล้ว

    nice !!

  • @houstonbova3136
    @houstonbova3136 11 หลายเดือนก่อน +1

    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

  • @epicanthus
    @epicanthus ปีที่แล้ว +5

    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.

  • @naturfagstoff
    @naturfagstoff ปีที่แล้ว +15

    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 ปีที่แล้ว +1

      you have to adopt changes
      Else: you'll be left behind

    • @joseoncrack
      @joseoncrack 9 หลายเดือนก่อน +1

      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 หลายเดือนก่อน +1

      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.

  • @fromgermany271
    @fromgermany271 ปีที่แล้ว +3

    So what‘s complained about in C(++) for decades is now honored for keystroke saving in other languages as well 😂

  • @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(...)

  • @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 ปีที่แล้ว +2

    How to change the appearance of the arrow used for function annotations from "->" to a unicode arrow symbol?

    • @Indently
      @Indently  ปีที่แล้ว +2

      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

  • @xzex2609
    @xzex2609 ปีที่แล้ว +9

    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

  • @leightaylor8069
    @leightaylor8069 ปีที่แล้ว +3

    Good video. The feature of Python I see underused a lot is the "dict.setdefault" method.

    • @Indently
      @Indently  ปีที่แล้ว +1

      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.

  • @Bl0xxy
    @Bl0xxy 2 หลายเดือนก่อน

    I use the walrus all the time with input() uses in if statements

  • @gardnmi
    @gardnmi ปีที่แล้ว +4

    The operator that made Guido quit python.

    • @DrDeuteron
      @DrDeuteron ปีที่แล้ว

      well that explains it.

  • @EW-mb1ih
    @EW-mb1ih 28 วันที่ผ่านมา

    Does this operator give any gain in speed performance ?

  • @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

  • @eugenewii
    @eugenewii ปีที่แล้ว +1

    I thought I was the walrus, but maybe I'm the egg man.

    • @nbme5804
      @nbme5804 ปีที่แล้ว +1

      Koo Koo kachoo!

  • @josgibbons6777
    @josgibbons6777 11 หลายเดือนก่อน

    I can't believe you didn't mention while loops.

  • @michaelemulu
    @michaelemulu ปีที่แล้ว

    I learned sth. Thank you

  • @jello195
    @jello195 9 หลายเดือนก่อน

    why do yo declare variable as
    variable_name : type = x
    instead of
    variable_name = x
    ?

  • @Pawlo370
    @Pawlo370 25 วันที่ผ่านมา

    okay now i'm understand

  • @athulkrishnadiyil1735
    @athulkrishnadiyil1735 9 หลายเดือนก่อน

    i got an instant rejection in an interview for not having good knowledge about this so called Walrus operator.

  • @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

  • @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 ปีที่แล้ว +1

      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.

  • @MarcoAntoniotti
    @MarcoAntoniotti 6 หลายเดือนก่อน

    Ok. It took about 30 years to get this in Python.

  • @cgyh68748
    @cgyh68748 ปีที่แล้ว

    How have I never seen this in a coding video before?

  • @gustavomaia2252
    @gustavomaia2252 ปีที่แล้ว

    How did he put a thumbs up in a string? 😂😂

  • @jackytaly
    @jackytaly ปีที่แล้ว +3

    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 ปีที่แล้ว +1

      @@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 ปีที่แล้ว

    🙏👍

  • @elmussom5433
    @elmussom5433 ปีที่แล้ว

    Im suprised nobody invented this earlier. I needed this operator for many years

  • @tihon4979
    @tihon4979 4 หลายเดือนก่อน

    PEP 20:
    Explicit is better than implicit....

  • @AlexCernat
    @AlexCernat ปีที่แล้ว +1

    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 :-)

  • @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 ปีที่แล้ว +1

      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.

  • @TSPxEclipse
    @TSPxEclipse หลายเดือนก่อน

    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.

  • @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.

  • @HoSza1
    @HoSza1 ปีที่แล้ว +1

    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)

  • @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 🤣

  • @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.

  • @KeithKazamaFlick
    @KeithKazamaFlick 8 หลายเดือนก่อน

    :=

  • @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.

  • @valorien1
    @valorien1 5 หลายเดือนก่อน +1

    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.

  • @davea136
    @davea136 29 วันที่ผ่านมา

    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!

  • @DrDeuteron
    @DrDeuteron ปีที่แล้ว

    I don't think I like type hints.

  • @sh1maru
    @sh1maru ปีที่แล้ว

    This operator literally killed python

    • @Indently
      @Indently  ปีที่แล้ว +2

      Yeah, Python was never used again by anyone after this sugar syntax