Python's Walrus Operator??

Поделиться
HTML-код
  • Опубликовано: 11 сен 2024
  • ⭐ Join my Patreon: / b001io
    💬 Discord: / discord
    🐦 Follow me on Twitter: / b001io
    🔗 More links: linktr.ee/b001io
    Background Music:
    Slowly by Tokyo Music Walker | / user-356546060
    Music promoted by www.free-stock...
    Creative Commons / Attribution 3.0 Unported License (CC BY 3.0)
    creativecommon...

Комментарии • 236

  • @xonxt
    @xonxt Год назад +428

    An obvious note is that the Walrus Operator only appeared since Python 3.8, so if you have to work on older systems, it will not be backwards compatible...

    • @aw1lt
      @aw1lt Год назад

      backwards compatible code is retarded. why not just code on the lowest version you want to run it on? that way if it runs on your machine, it (likely) runs on all versions above

    • @werakoko
      @werakoko Год назад +16

      From my experience using python software, it is the forward compatibility you should care about.

    • @aw1lt
      @aw1lt Год назад +3

      @@werakoko thats what im saying

    • @sgt391
      @sgt391 Год назад +9

      I like using modern syntax to bully my coworkers that keep using 3.7 for whatever reason.

    • @em_the_bee
      @em_the_bee Год назад +3

      Why doesn't regular assignment work? Works in Ruby where everything (including assignment) is an expression; and the if statement evaluates expressions.

  • @nicktreleaven4119
    @nicktreleaven4119 Год назад +143

    Another nice example from the PEP with while:
    while chunk := file.read(8192):
    process(chunk)
    You can't rewrite that without having to change the control flow.

    • @tariq4119
      @tariq4119 Год назад +4

      thank you. will def use this

    • @bultvidxxxix9973
      @bultvidxxxix9973 Год назад +26

      Sure you can.
      while True:
      chunk = file.read(8192)
      if not chunk:
      break
      process(chunk)
      This construct is called a Loop-and-a-half and very helpful sometimes. Using the assignment in the condition is a very common concept in C code and more concise. But for more complex loop setups than a simple assignment you want to use the long form instead of crunching 200 characters into the condition. The control flow is the same.

    • @nicktreleaven4119
      @nicktreleaven4119 Год назад +13

      @@bultvidxxxix9973 you are using an extra control flow statement

    • @sierravanriel6906
      @sierravanriel6906 Год назад +5

      What about:
      chunk = file.read (8192)
      while chunk:
      process (chunk)
      chunk = file.read (8192)
      Wouldn't that have the same control flow?

    • @nicktreleaven4119
      @nicktreleaven4119 Год назад +6

      @@sierravanriel6906 yes but it's not DRY. You have to remember to update the chunk size in two places (if you want to change it), and the loop body might be long.

  • @AetherBreaker1
    @AetherBreaker1 Год назад +141

    Something worth noting about the walrus operator, is that it always "returns" the value of the variable, unlike a regular assignment operation (eg: x = 10), this is why it works inside stuff like an if statement or inside other operations.
    In python, you have assignments, and expressions, you can assign an expression to something, but you cannot perform a normal assignment inside an expression because a normal assignment doesnt return anything.

    • @chri-k
      @chri-k Год назад +1

      assignments don’t return anything in python?!

    • @UnlikelyToRemember
      @UnlikelyToRemember Год назад +6

      As a C programmer, that's really weird! In C, just: if ((n = count_odds(data)) > 1) ...

    • @bloodgain
      @bloodgain Год назад +9

      @@UnlikelyToRemember Except that because it's so easy to accidentally use '=' instead of '==', lots of bugs are introduced this way. It's so common that the de facto usage pattern has become `if (CONST == myVar)` to throw a compiler error in the case of an accidental assignment operator use. This is why so many modern languages stopped allowing it, only to realize it is sometimes very useful, so introduced a much less error-prone syntax for it.

    • @UnlikelyToRemember
      @UnlikelyToRemember Год назад +1

      @@bloodgain Compilers have been warning about "if (a=b) ..." for at least 2 decades now. But, some people just aren't cut out to be programmers.

    • @bloodgain
      @bloodgain Год назад +5

      @@UnlikelyToRemember So, your option is to either turn off warnings for that or ignore them? Hmm. I prefer to deal with compiler warnings. But I guess some people just aren't cut out to be _good_ programmers.

  • @finnthirud
    @finnthirud Год назад +5

    I love that you added the "obvious" method which makes for a great explanation of when to choose what, i.e. readability. Great tutoring. Thank you! :=

  • @tiny0pus
    @tiny0pus Год назад +100

    Dude I'm a freshman taking APSCP, our teacher is teaching VIA python. I've picked up on it fast, but a lot of advanced stuff like this is hard for me (Especially since we're working on AP task). I really appreciate the tricks and tips you provide!

    • @snesmocha
      @snesmocha Год назад

      isn't the ap program java only for the exam........

    • @sklnet9537
      @sklnet9537 Год назад

      @@snesmocha The AP test is psuedocode, Create PT is whatever you want

    • @Emily-fm7pt
      @Emily-fm7pt Год назад +1

      @@snesmocha I think AP CS Principles is mainly in Python, and I think it covers a more 'high-level' overview that you'd see closer to IT rather than CS (though tbf neither really cover all that much soooo). It's different than the CS A class which just covers Java (ughh...)

    • @tiny0pus
      @tiny0pus Год назад +3

      @@snesmocha No APSCP is in any language, including block based like scratch. I think APSCA might be java only though, not sure

    • @eli334-1
      @eli334-1 Год назад

      @@Emily-fm7pt My school's teaching JS for APCSP, and AP CS A is in Java, so I think AP CS Principles is in any language, and I bet CS A is Java-only.

  • @nicktreleaven4119
    @nicktreleaven4119 Год назад +19

    It can also avoid indentation. Before:
    match1 = pattern1.match(data)
    if match1:
    result = match1.group(1)
    else:
    match2 = pattern2.match(data)
    if match2:
    result = match2.group(2)
    else:
    result = None
    After:
    if match1 := pattern1.match(data):
    result = match1.group(1)
    elif match2 := pattern2.match(data):
    result = match2.group(2)
    else:
    result = None
    Example from the PEP.

    • @baliDOTid
      @baliDOTid Год назад

      why u type match1 = pattern1.match(data) outside of clause but match2 = pattern2.match(data) inside the clause in the first one?

  • @foreverunsure
    @foreverunsure Год назад +11

    wow, this was an easy and straight to the point explanation, thank you!

  • @davidking4978
    @davidking4978 Год назад +6

    Historical note from an old-timer:
    We never thought to call it "the walrus operator" but . . .
    Going back DECADES the := operator was used in Algol and derived languages (like Pascal) . . . for assignment statements.

  • @fllthdcrb
    @fllthdcrb Год назад +40

    I didn't know something like this was in Python. Very interesting. This is very similar to the "=" operator in C, except that can be used for assignment anywhere in an expression, including something that looks like Python's assignment statements. The problem with that is it's quite easy to accidentally turn the equality operator "==" into the assignment operator, especially in conditions, where it will cause an assignment and make the condition succeed when it shouldn't. It's good practice to use parentheses to make deliberate embedded assignments clear, and some compilers can detect if you don't. But I like this approach, of requiring you to write a different operator if you really mean to do this.

    • @Turalcar
      @Turalcar Год назад +6

      In C++17 you can declare variables in if and while as well:
      if (int n = stuff()) {
      stuff_with(n);
      }

    • @glarynth
      @glarynth Год назад +1

      Python's := has annoyingly low precedence, so you often end up with lots of parentheses anyway.

  • @IceMetalPunk
    @IceMetalPunk Год назад +13

    As someone who works with JavaScript far more than Python, I was just thinking, "wait, isn't that just how assignment works anyway?" 😅

    • @TrueThanny
      @TrueThanny Год назад +1

      In C-derived languages, at least.
      For me, the odd thing was the term "walrus operator", which I had never heard before. Took a second to figure out where the name came from.

    • @sonicsplasher
      @sonicsplasher 8 месяцев назад

      @@TrueThanny Isn't python a C-derived language?

    • @TrueThanny
      @TrueThanny 8 месяцев назад

      @@sonicsplasher In no way whatsoever is Python derived from C.
      Have you ever written code in either one?

  • @stefaanverstraeten9291
    @stefaanverstraeten9291 Год назад +5

    Anybody else remembers this as the standard assign statement from Pascal?

  • @rask004
    @rask004 Год назад +3

    This is interesting to know and I appreciate how such syntactic sugars are useful. Also, I've encountered many situations where the use of such specific or unique syntax make reading the code more effort-full, which especially in teams and with team communication can slow development. Personally, if it can be done in a way which is faster to comprehend without major impacts to other aspects of the development cycle or to product maintenance, then that way is preferable.
    Also, I cannot get the similarity of a C-syntax variable assignment inside a control structure's condition evaluation out of my head.

  • @Spencer-wc6ew
    @Spencer-wc6ew Год назад +1

    An important note:
    Always surround it with parenthesis!
    "if x:=y == 0:" isn't a syntax error, but it doesn't set x to y. It sets x to "y == 0".
    Also "x = y = 0" is valid python that sets x and y to 0. That makes it look like "y = 0" evaluates to 0. But it doesn't evaluate to anything. You can't use a single equals in an if statement like in C.

    • @Tresla
      @Tresla Год назад

      if "y = 0" doesn't evaluate to anything, what would the value of x be in the statement "x = y = 0"?

    • @InigoPhentoya
      @InigoPhentoya Год назад +1

      Normally we think of 'evaluating' as getting the return value of an expression. However, in Python, assignments do not have return values (as opposed to languages like C, where a return value might be needed to verify an assignment succeeded). The assigned value of x will be 0, but neither of the statements "x = y = 0" and "y = 0" evaluate to anything. This is what the walrus operator is meant for, by the way -- it allows you to both make the assignment and evaluate the expression (it's actual name is the 'assignment expression operator').

  • @MajesticUC
    @MajesticUC Год назад +7

    this is why I love python. I don't actually use it because I don't have any reason to but it seems like such a useful language. I do c# and lua btw

    • @wontcreep
      @wontcreep Год назад

      i find it extremely annoying and costly to deal with no typing, making it so you are expected to implement every piece of code correctly together (no warnings) or else you get runtime errors; Also doing a lot of try/catches to validate user input, i mean, they call them exceptions yet everyone expects them and put them in handles...
      though i've seen a lot of smart people being very skilled at this language, i simply don't get them, from experience i've come to love Typescript as a weakly typed scripting language

  • @FreshSmog
    @FreshSmog Год назад +21

    Fancy operators like this usually end up not transferable to other languages, and are extremely unreadable to other programmers who aren't used to this particular language. It's not worth sacrificing readability when it's only going to save a line or two.
    I made the mistake of learning all the quirky syntactic sugars in JS/TS, and only ended up confusing the heck out those working with me. I'm never going to let that happen again. If you can't be sure you everyone who works with you has the same dedication to python and niche python features, just use the standard syntax.

    • @zedeps
      @zedeps Год назад

      I mean, from what it looks like to me, the walrus operator isn't only for reducing lines of code, but also can be used for optimizing the code and reducing redundancies in calculations and such. It may make the code more difficult to read in a collaborative setting, but may still be useful for optimizing performance.
      I might just be talking out of my ass though, I just started learning to code a month ago at the end of an unrelated bachelor's degree. I don't really know how things work in the real world.

    • @Nilmil_0838
      @Nilmil_0838 Год назад +2

      @@zedeps you can still optimize while not sacrificing readability, maybe for lowering memory storage if the n:= is erased right after the comparison.

    • @riddle-me-ruben
      @riddle-me-ruben 8 месяцев назад

      I was thinking.. You can just assign the return value to a variable first, then use it wherever necessary.
      n = function(array)
      if n > 1:
      # process
      Other than aesthetics.. does this serve any other purpose?

  • @christosmantas4308
    @christosmantas4308 Год назад +3

    I really like these style of `if` predicates and did not know about this operator.
    Thanks

  • @waiitwhaat
    @waiitwhaat Год назад +1

    The walrus operator is an absolute gem for one liner codes. It's been a nightmare for me to work without it because I'm forced to use Python 3.6 ;-;

  • @DonCDXX
    @DonCDXX Год назад

    I don't really need Python tutorials right now. This was recommended after I looked at C# tutorials, of which I am currently expanding my knowledge. It just interested me because I had never heard the walrus operator before.
    I have to say that the clarity, conciseness, and simplicity of the explanation is exactly what I wish I could find in the videos I've been looking for, but unable to find so far, regarding C#. This is an example of what people want in these types of videos done perfectly.

  • @lily_littleangel
    @lily_littleangel Год назад +1

    Guess it makes sense to use this symbol, as := is also used in mathematics to denote assignment, e.g.:
    "Let 2 := 1 + 1 denote the successor to 1.".

    • @MrCmon113
      @MrCmon113 6 месяцев назад

      Assignment is already "=" as in any modern programming language.
      And what you wrote there is grammatically really wonky. Usually one would write "Let 2 be 1+1". Or just "2:=1+1". Because in mathematics ":=" is not a walrus operator.

  • @Portponky
    @Portponky Год назад +2

    Immense disrespect to the case where you have only one odd number.

  • @therealestfortex
    @therealestfortex Год назад +6

    I think I'm more surprised you can make lists like that than learning about this operator

    • @oussamabr5851
      @oussamabr5851 Год назад +2

      It's a pretty cool way of doing it, and It's called list comprehension in the case of lists. There's also tuple comprehension, dictionary comprehension and set comprehension.
      It's a neat way to create iterables in one line instead of many.

    • @zecuse
      @zecuse Год назад +3

      Ya, and list comprehensions can be nested in each other:
      transpose = [[row[i] for row in matrix] for i in range(len(matrix))]

  • @fairphoneuser9009
    @fairphoneuser9009 Год назад +7

    So this does the same as the = in almost any other language? 😱

    • @dominat0r3600
      @dominat0r3600 Год назад +3

      No, it does the same as = does in python too.
      It specifically allows you to make in-line assignments in places you otherwise wouldn't.
      It's nearly useless in actual code to be honest, because it's cleaner to put the equation 1 line up and simply call the variable instead of using := which in this case is python specific

    • @erikkonstas
      @erikkonstas Год назад +3

      @@dominat0r3600 Except that that's exactly what they're saying... "= in other languages" means that = can be used in an expression, while Python forbids this.

    • @TrueThanny
      @TrueThanny Год назад

      @@dominat0r3600 You've apparently never seen C code.

  • @GuagoFruit
    @GuagoFruit Год назад +1

    I used to do this a lot in C, but forgot that it exists in Python so thanks for reminding me.

  • @cleverclover7
    @cleverclover7 Год назад +2

    Seeing as you had to make a video to explain what it does I would argue assigning to the variable is more easily understood. Good video.

    • @nicktreleaven4119
      @nicktreleaven4119 Год назад +2

      Then the variable is in a larger scope than necessary. When refactoring and testing you might accidentally use it which can hide a bug.

    • @cleverclover7
      @cleverclover7 Год назад

      @@nicktreleaven4119 make smaller functions in that case to limit the scope. Can't see myself ever using walrus operator, sry.

    • @nicktreleaven4119
      @nicktreleaven4119 Год назад

      @@cleverclover7 it's still more bug prone in practice. Best practice is to keep variable scopes small. This helps. In more complex code it also helps to simplify nesting (see my top level reply if interested).

  • @LouisDuran
    @LouisDuran Год назад

    Thank god for making this short. Other videos are like 12 minutes to talk about one f'ing operator

  • @TheOtherSteel
    @TheOtherSteel Год назад +1

    The text size in the video thumbnail was nice, but in the video was so tiby I couldn't read it.

  • @turglow01
    @turglow01 4 месяца назад

    exactly what i was looking for, thanks

  • @Yutaro-Yoshii
    @Yutaro-Yoshii Год назад +2

    In languages that support expression assignment it would be much easier. Python took the shortcut and hard coded many things to be multi line, so this is the price we have to pay to write concise code.

    • @Sarmachus
      @Sarmachus Год назад

      Can you give an example of expression assignment?

    • @Yutaro-Yoshii
      @Yutaro-Yoshii Год назад

      ​@@Sarmachus
      common patterns that I seen in js/typescript/c
      //javascript/typescript
      let result: null|Result;
      if(result = someOperation()){//returns instance of Result or null, which is falseish
      //do something with result, now that you know it's not null
      }
      //c
      data_type* some_ptr;
      if(some_ptr = get_obj()){//returns NULL or pointer to data_type
      //do something with some_ptr, now that you know it's not NULL.
      }
      ```

    • @Sarmachus
      @Sarmachus Год назад

      I see. Makes sense, though I don't see how it is significantly different from := in python. It's all syntax in the end.
      I do like having the variable declared ahead of time though.

    • @Yutaro-Yoshii
      @Yutaro-Yoshii Год назад

      ​@@Sarmachus Yeah, it's not that of a big deal indeed since it's just a single character. But I do think that it is kind of confusing because := is used as declaration in languages like go, but not for assignment. But in python := and = do essentially the same things if my understanding is correct.
      But overall I love this new feature now that I can use the same conditional assignment patterns that I see in other languages.

  • @Franfran722
    @Franfran722 Год назад +2

    For while statements it can be great !

  • @VioletCatastrophe
    @VioletCatastrophe Год назад +5

    I feel like a lot of python is about writing fewer, more dense lines of code. And I honestly feel like its really bad practice in many cases. For this example, I'd assign the count to a variable, naming it in a descriptive way, and then perform the if > print block. In a few situations python has some really cool stuff that is human readable and dense, like 'o for o in data if 0%2==1', which I really like about the language, but so many of these things can be misused. At least from this example I can't see any use case for this operator outside of code golf.
    Maybe it's just me, but I like to write more lines, have each line be clear in its purpose, and when things get too long I separate it into a function so that it stays a single line which now has a function name that describes the process. It's simple self-documenting code, which 'pythonic' solutions often end up being the exact opposite of.

    • @byetaeyang
      @byetaeyang Год назад +2

      This sort of control flow is actually much more common and considered "good practice" in other languages albeit with slightly different syntax. Rust and Swift implement this feature with the "if.. let" syntax and tends to be preferred due to the added benefit of not needing to store the state of the return value outside of conditional scope. This last point becomes more apparent when dealing with multiple return types as now instead of having multiple variables possibly clashing in the outside namespace, they are appropriately initialized within the intended scope.

    • @flam1ngicecream
      @flam1ngicecream Год назад +1

      In this case, I wouldn't even include the "==1" in that odd check since 1 is already truthy

  • @gamerk316
    @gamerk316 Год назад

    You can do this in other languages (like C) too; it's *heavily* frowned upon because it violates the principle that one SLOC should do exactly one thing in order to prevent any unintended behaviors that go unnoticed by combining operations.

  • @anon_y_mousse
    @anon_y_mousse 9 месяцев назад

    Interesting that Python added that. A few other languages already did things this way, like both Go and Pascal. I liked it so much that I copied that for my own language.

  • @lirsanplay9196
    @lirsanplay9196 Год назад +2

    I like what i saw on your channel so far.
    I suggest video about lambda functions. Especially in list comprehintion.
    For me, at was always something strange, what i forget every time i learn it.

  • @LukeVilent
    @LukeVilent Год назад

    Actually needed this earlier today.

  • @Fine_Mouche
    @Fine_Mouche Год назад +1

    Maybe n:= can be use to encapsule some private calculation. I don't know.

  • @csori1075
    @csori1075 Год назад +4

    can you do a video on decorators please? good content as always

    • @b001
      @b001  Год назад +3

      Yes, check out the video I posted before this one!

  • @asainpopiu6033
    @asainpopiu6033 Год назад +1

    Noooo! You need to fix that silly missing space! Aaaaaaaaaa

  • @scaffus
    @scaffus Год назад

    My god I've been missing out on this one, thank you very much

  • @NowLP
    @NowLP Год назад +2

    fascinating, I have wondered if something like this exists in python, since it does in e.g. Swift and theoretically Rust

  • @carlfranz6805
    @carlfranz6805 Год назад +1

    I'm really going to have to look back on the discussion on this operator because I just don't see the point.

  • @ryankhart
    @ryankhart Год назад +1

    Good content, but I wish the font was larger so that I can read it from my phone screen without going full screen.

    • @TrueThanny
      @TrueThanny Год назад

      Stop watching videos on a tiny screen then complaining about the consequences of your choice.

    • @ryankhart
      @ryankhart Год назад

      @@TrueThanny If I see a video on RUclips that I want to watch, and I'm on mobile, I'm gonna watch it on mobile, not wait until I'm back at my desktop. Otherwise, why would I be on the RUclips app on my phone if I didn't want to watch videos?

    • @TrueThanny
      @TrueThanny Год назад

      @@ryankhart Fine, but you need to accept the limitations that result from your choice, rather than demand the video be made worse for everyone viewing it on a proper display.

    • @ryankhart
      @ryankhart Год назад

      @@TrueThanny Why would the video be made worse for everyone. It's harder to make the video for the person recording because they have to pay more attention to making sure the relevant text is on screen at any given time. Larger text is worse for multitasking, for sure. But in a video format, there's no need for multitasking. It's a linear format.
      Plus, think of the missed opportunity not using a large font size and a competing channel comes along and has a large font size stealing viewership away from your channel.

  • @xanderlastname3281
    @xanderlastname3281 Год назад +1

    Two weeks ago?
    Didn't I watch this a year ago?
    (Is this a reupload)

  • @AdityaSharma-wg4rj
    @AdityaSharma-wg4rj Год назад +1

    nice way to explain is such a easy manner

  • @OtateriheemEdRiemLav
    @OtateriheemEdRiemLav Год назад

    I was searching for that, thank you

  • @somerandomdude4588
    @somerandomdude4588 Год назад

    You’ve gotten yourself a new sub

  • @polychad
    @polychad Год назад +1

    Welcome to another addition of "Catching up to the mess that is JavaScript" ep.4

  • @680x0
    @680x0 Год назад +1

    Oh look! Python is finally catching up with C, C++, Java, etc. :-D

  • @MarcelSchliesser
    @MarcelSchliesser Год назад +1

    Like the theme, which one is it? :)

  • @AlexAegisOfficial
    @AlexAegisOfficial Год назад +1

    PEP20, the zen of python: "There should be one-- and preferably only one --obvious way to do it."
    Yeah. What a lie.

  • @asdasx392
    @asdasx392 Год назад +1

    I completely don't get why this feature is necessary. I don't think it is a good idea to keep making changes to a language without there being some significant value to it, In other words, only make the change if the value of the change exceeds the problems caused by an increasingly changing language. Furthermore, to do something link that in C (assignments within if conditions) would be considered a bad practice and source of bugs. From what I see on RUclips, Python programmers seem to love these continuous little tweaks, but I just don't see the value.

    • @MrCmon113
      @MrCmon113 6 месяцев назад

      The exact opposite is true.
      Lots of Python programmers hated this addition and it was probably made to appease people coming from C or other languages in which assingments return their values by default.

  • @dimaryk11
    @dimaryk11 Год назад

    Walrus is similar to C's arrow notation - it allows you to write less code

  • @zdrux
    @zdrux Год назад +2

    Nice!

  • @pedrosso0
    @pedrosso0 Год назад

    Looks at the thumbnail
    "It's the define operator!"
    Remembers that definitions already work by =
    "Oh..."
    You know, programming languages should start using := to assign new values and = to check them

  • @sosisje
    @sosisje Год назад

    Seems usefull within listcomprehensions

  • @pigsareit
    @pigsareit Год назад

    I can't read what you're typing, there's this humongous "includes paid promotion >" button on mobile covering your code.

  • @TylerDurdenFcS
    @TylerDurdenFcS Год назад +2

    Can you please share your extensions in vs code and the theme? 😊

  • @tapifier
    @tapifier Год назад +1

    Can you please make a tutorial on how to create an exe for the python project? I tried pyInstaller but antivirus detects my app as a trojan

  • @gagemonster555
    @gagemonster555 Год назад

    idk man i'm just listening to the first second of "what is the walrus" and thinking about lennon

  • @qloxer1264
    @qloxer1264 Год назад

    Omg i had no idea this existed tysm

  • @AmCanTech
    @AmCanTech Год назад

    Time isnt really a good way to measure performance as it varies by cpu and computer and interpreter

  • @Jelte_Dijkmans
    @Jelte_Dijkmans Год назад

    its quite useful if you want to do things in minimal lines, so like:
    n=1
    while True:
    print(n:=n+1)

    • @davidtejuosho587
      @davidtejuosho587 Год назад

      n=1
      while True:
      print(n+=1)
      that works the same, no?

    • @Jelte_Dijkmans
      @Jelte_Dijkmans Год назад

      @@davidtejuosho587 no actually, that gives a syntax error, as it only results in the fact it has been stord, and not any values, for sure not n

  • @zobiah1
    @zobiah1 Год назад

    im pretty sure that everything you called a second was a millisecond

  • @basharat4693
    @basharat4693 Год назад +1

    Can someone tell me why my VS code doesn't show the result directly but show extra details of the folder and stuff before giving the output ?

  • @TechySpeaking
    @TechySpeaking Год назад +1

    So... it saves a single line.

    • @gac7527
      @gac7527 Год назад

      and (seemingly) doubles performance…

  • @numoru
    @numoru 8 месяцев назад

    oh ok now I know what im doing today

  • @Mernom
    @Mernom Год назад

    Is the variable only in scope inside the condition if this is used? If not, then it looks like just a typing saving thing, rather than anything actually useful.

  • @shaqtaku
    @shaqtaku Год назад +1

    what color scheme are you using for vscode

  • @ItsSB
    @ItsSB Год назад

    Very informative video, btw which theme is it?

  • @MH-oc4de
    @MH-oc4de Год назад

    Good to know - I start to type something like this in python and then realize it doesn't exist. Now it does!

  • @LUKAS-bb4jc
    @LUKAS-bb4jc Год назад

    Nice video what theme is that ?

  • @puppergump4117
    @puppergump4117 Год назад +1

    Good explanation, but I see no reason to use this operator. If you ever need to use this you may as well use ternaries.
    I also checked with c++ that the evaluation of an assignment expression returns the variable. This means an equals sign here would work just as well. It also returns the pointers of strings so those work too.

    • @Spencer-wc6ew
      @Spencer-wc6ew Год назад +1

      That's C++, this is Python. In Python, the evaluation of an assignment does not return the variable. "if (x = y) > 0:" is a syntax error, but "if (x := y) > 0:" is not

    • @Spencer-wc6ew
      @Spencer-wc6ew Год назад

      And how does a terniary operator work in its place?
      You'd still have to add another line to save the result to a variable or call it twice in the terniary statement. And with an if statement, you can run as much code as you want in the body. A terniary statement just lets you run 1 expression in the if and 1 in the else sections.

    • @puppergump4117
      @puppergump4117 Год назад

      @@Spencer-wc6ew I thought python was about usability, why do they not let assignments return anything?

    • @goosydev
      @goosydev Год назад

      I agree, why cant people just use normal variables and name them properly. This just makes you use a one character variable which isn't helpful, or write a long if statement which is also a bad practice. Write clean code not cool code. But its cool to know about ig. Python could just invest some more efforts in shipping useful tools and no code-shorteners (Like proper typing/linting support)

    • @puppergump4117
      @puppergump4117 Год назад

      @@goosydev Well we always have rust

  • @wisteela
    @wisteela Год назад

    That's a great name for it.

  • @Maiska123
    @Maiska123 Год назад

    As a mobile viewer, you really using fullscreen capture to show around 20% of the screen?😅 just a tip that fontsize could be greater!

    • @TrueThanny
      @TrueThanny Год назад +1

      Why should the presentation be marred to accommodate someone who chose to watch the video on a tiny screen?

    • @Maiska123
      @Maiska123 Год назад

      @@TrueThanny as a frequent mobileviewer - it is just a convenience, not to critisize content itself - and still makes video more approachable when seeing clearly what is changing and when (if not excessive animations etc. Used). So its always better from viewers perspective to have clear view of the thing you are supposed to show - podcasts are different thing.

    • @Maiska123
      @Maiska123 Год назад

      @@TrueThanny and to be clear - while intent is good, and content is flawless - execution itself can be improved.

    • @TrueThanny
      @TrueThanny Год назад

      @@Maiska123 The execution is as good as it can be. Zooming in on the text would be _worse_ execution. You aren't writing Python code on your phone. Nobody does that unless it's an emergency and they're not near a proper computer.
      This video is for people writing Python code for one reason or another. It's suitable for viewing on a proper computer, not for somebody killing time by watching videos on a device that's poorly suited to that task.

  • @patrickwienhoft7987
    @patrickwienhoft7987 Год назад +1

    Additional use but also a potential pitfall is that the statement still evaluated lazily.
    E.g. if I only wanted to print the data if its length is even:
    if len(data)%2==0 and (n:=count_odds(data) > 1):
    print(f"{n} odds")
    So in this example we could easily skip the if statement without running count_odds.
    The equally fast alternative would be:
    if len(data)%2==0:
    n =count_odds(data):
    if n > 1:
    print(f"{n} odds")
    So here, it does not only save a line, but even a level of nestings.
    You have to be careful tho as you can not be sure that n is defined afterwards, as count_odds did not run. So this should only be used if you use the variable within the loop but not after.

  • @mountain2017
    @mountain2017 Год назад

    wow that was amazing !

  • @platonicvulpine
    @platonicvulpine Год назад

    You've somehow missed all the important details, namely:
    - when the operator was added
    - the 'while' use case
    - clearly stating its precedence
    - the scope of the variable it defines
    And you focused on 'how not to call a function twice', which is arguably not an issue most people would have?
    It is genuinely a better use of time to read the docs than to watch this video.

  • @kino9521
    @kino9521 Год назад

    Very cool, but I'd still use a variable to store the value, seems more familiar and it's pretty self explanatory

    • @InigoPhentoya
      @InigoPhentoya Год назад +2

      It does assign it to a variable.

    • @kino9521
      @kino9521 Год назад +1

      @@InigoPhentoya Yes, i know, I meant explicitly assigning it to a variable like what he did at the end of the video

  • @MikeGranby
    @MikeGranby Год назад

    So it’s the like the assignment in proper languages? ;)

  • @raghul2904
    @raghul2904 Год назад +1

    Do more videos for beginners

  • @Awesomo4000
    @Awesomo4000 Год назад +1

    Not relevant, but why add comments for t1 (Start time) and t2 (End time) instead of just calling the variables startTime and endTime?

    • @kovec681
      @kovec681 5 месяцев назад

      Thank you! (although i prefer snake case...)

  • @TheFreeSpiritKID
    @TheFreeSpiritKID Год назад

    Please put spaces left and right of your mathematical operators. Makes any code so much more readable

  • @reaper6341
    @reaper6341 Год назад +1

    bro theme?

  • @YamiZee
    @YamiZee Год назад

    I now understand how it works, but I'm not convinced it's useful. Seems like it makes code harder to read

  • @user-qy3hs2ju3r
    @user-qy3hs2ju3r 2 месяца назад

    It is nice explanation

  • @gipen
    @gipen Год назад

    in php you can just use "=", i don't get why the extra ":"

  • @dipeshsamrawat7957
    @dipeshsamrawat7957 Год назад

    Excellent ❤

  • @kebman
    @kebman Год назад

    The walrus operator honestly seems like Perl creep. And I don't mean that in a good way. It means the code gets less legible, unless you know the fnnnthy small squiggles. For that reason it's pretty obvious that declaring your variables before the computation is a good practise, especially in a language that was built to be more legible in the first place.

  • @kaddasixseven3581
    @kaddasixseven3581 Год назад

    But why does it have to be a new operator? Other languages can just do this with the assignment operator (=)

    • @epsi
      @epsi Год назад

      And BASIC used = for both assignment and equality:
      REM Compare X = 0 and assign result to V.
      V = X = 0
      And PL/I is infamous for not having reserved keywords:
      IF IF = THEN THEN THEN = ELSE ELSE ELSE = IF
      Why did C and so many other languages choose == for equality?
      or
      Why did Pascal choose := for assignment?
      or
      Why do programming languages reserve keywords?
      The answer is simple: because that's just how they decided to do it.

    • @MrCmon113
      @MrCmon113 6 месяцев назад

      Yeah and it's an endless motor of bugs.

  • @okunamayanad
    @okunamayanad Год назад

    is it just me seeing an eggplant in :=

  • @feyh
    @feyh Год назад

    Your video is more useful than the walrus operator!

  • @Ahmed-iam
    @Ahmed-iam Год назад

    I was searching for this

  • @misaalanshori
    @misaalanshori Год назад +1

    Why doesn't it just use regular =?

    • @InigoPhentoya
      @InigoPhentoya Год назад

      Python assignments do not have return values.

    • @misaalanshori
      @misaalanshori Год назад +1

      @@InigoPhentoya then why not make the regular python assignments return values instead of making a new assignment operator that does return a value?

    • @InigoPhentoya
      @InigoPhentoya Год назад

      @@misaalanshori It is much, much easier to add an operator that does some new thing than to change something fundamental about an existing thing, especially in the context of backwards compatibility.

    • @misaalanshori
      @misaalanshori Год назад

      @@InigoPhentoya would making the assignment operator return a value really effect backwards compatibility? I feel like since it wasn't a feature before then no one would be using it to get a value, in fact using an assignment as a value gives a syntax error, so i feel like there would be no program that uses the assignment operator in this way. So adding this feature shouldn't break existing code.
      Can you share an example where making this a feature would break something? (I haven't done any research on this tbh)

    • @MrCmon113
      @MrCmon113 6 месяцев назад

      @@misaalanshori
      Because that would completely break earlier code.
      E.g. a=b=1 asigns both a and b the value of 1 as it stands. If assignments had return values, you'd have to change other parts of the language.

  • @shrigley4500
    @shrigley4500 Год назад

    what font is this?

  • @CZghost
    @CZghost Год назад

    No question asked, I can see very clearly why it's called a "walrus" operator :D

  • @westerp
    @westerp Год назад

    Crazy python to use ALGOL assignment operator, which you call the walrus operator, for assignment in an expression and C style for statements. I'm guessing this has to do with adding a feature to the language which doesn't affect the parser too much as I can't imagine it would break backwards compatibility to just add support for assignments in statements.

  • @redpz
    @redpz Год назад

    great videos

  • @DougGray-xf3hz
    @DougGray-xf3hz Год назад

    Microseconds?

  • @K0D0R0
    @K0D0R0 Год назад

    Using time.time() instead of time.perf_counter() 😢

  • @Milka-br1xw
    @Milka-br1xw 2 месяца назад

    What theme is he using?

    • @b001
      @b001  2 месяца назад

      Synthwave’84

  • @АлексейАгадилов

    Amazing