5 Cool Python One-Liners

แชร์
ฝัง
  • เผยแพร่เมื่อ 30 ก.ย. 2024

ความคิดเห็น • 125

  • @Slgjgnz
    @Slgjgnz 4 หลายเดือนก่อน +17

    If we are to mention golfing, let's go all the way.
    return ['No',Yes'][len(user_input)>10]+' case'
    or
    return 'YNeos'[len(user_input)

    • @south828
      @south828 3 หลายเดือนก่อน +5

      cursed 💣

  • @largewallofbeans9812
    @largewallofbeans9812 4 หลายเดือนก่อน +34

    One small thing of note: What you called the Elvis operator is actually Python's ternary conditional operator. Python's Elvis operator is 'or'.

    • @Indently
      @Indently  4 หลายเดือนก่อน +15

      Uff, thanks for bringing that to my attention! I absolutely meant to say ternary operator but somehow Elvis came to mind, I will update the description when I come back home :)

    • @felix30ua
      @felix30ua 3 หลายเดือนก่อน +1

      @@Indently len(user_input) > 10 and 'Yes case' or 'No case' ))))

    • @david-komi8
      @david-komi8 หลายเดือนก่อน

      ​@@IndentlyPretty funny that the description still hasn't been updated

  • @jogadorjnc
    @jogadorjnc 4 หลายเดือนก่อน +45

    The jumpscare at 2:30, lmao

  • @atnaszurc
    @atnaszurc 3 หลายเดือนก่อน +4

    Just a fyi, your email regex doesn't follow email standards. Domains are allowed to have characters outside of a-z, and so does the local part although it only works on a few mail servers. You'd be better of just checking for an @ sign surrounded by some text and periods.

  • @ego-lay_atman-bay
    @ego-lay_atman-bay 4 หลายเดือนก่อน +8

    I love line continuation, or at least putting arguments / parameters on their own line. It really helps when you have a bunch of parameters in a single function. It might also have something to do with the fact that I'm visually impaired, so I keep my zoom bigger, and I tend to have a smaller line length limit than most people (unintentionally, meaning, I just try to keep my code in view without having to scroll right, I don't pay attention to the number of characters in a line).

  • @DrDeuteron
    @DrDeuteron 4 หลายเดือนก่อน +3

    one liner for partitioning integers P(n, k):
    P = lambda n,k=None: (
    sum([P(n,j+1) for j in range(n)]) if k is None else
    0 if not n or k>n else
    1 if k==1 or k==n else
    P(n-1,k-1)+P(n-k,k)
    )

  • @volodymyrchelnokov8175
    @volodymyrchelnokov8175 4 หลายเดือนก่อน +2

    why would re.findall return a list[str | None] instead of just list[str]? An empty list is a perfectly valid list[str].

  • @thirdeye4654
    @thirdeye4654 4 หลายเดือนก่อน +1

    Regex is less painful than type annotations. :P By the way, a regex pattern using [A-Za-z0-9_] is just [\w]. I am also wondering who ever needs to reverse a string, is there a use case for it?

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

      As he mentioned, it works on any iterable and reversing a string is a common interview question for beginners (or at least used to be).

  • @xijnin
    @xijnin 4 หลายเดือนก่อน +20

    Readability is relative, some ppl think c++ is more readable than python lol

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

      he mean "Human readability"

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

      This is true to some extent, that's why they created industry standards/PEP

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

      Lol

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

      Human readability is relative only part of the time. Other things are clear cut, you can survey (multi-choice test) and you'll get a consistent answer (close to 100%).

  • @aaronvegoda1907
    @aaronvegoda1907 4 หลายเดือนก่อน +2

    When it comes to annotating something like that nested list, what I like to do is the following
    # MyPy does not love the new 3.12 type keyword. Eg (type IntOrStr = int | str) so
    from typing import TypeAlias
    # Quoting 'int | NestedList' is important, as we are forward referencing
    NestedList: TypeAlias = list["int | NestedList"]
    # And to make it generic
    from typing import TypeVar
    GenericNestedList: TypeAlias = list["T | GenericNestedList[T]"]
    # And to use it
    list_of_ints: NestedList = [1,[2,3,[4],5],6] # MyPy is happy
    list_of_bool: GenericNestedList[bool] = [True, [False, False], False, True] # Also happy
    I'm not sure what the typing docs have to say about this use case, but I haven't seen it discouraged anywhere either.
    If anyone does know what the typing docs have to say about this, please let me know :)

  • @MikePreston-darkflib
    @MikePreston-darkflib 4 หลายเดือนก่อน +1

    Just a note: trying to parse email addresses with a regex is very bad form. The userpart can be arbitrary and even include the @ sign itself - although pretty rare for modern email systems. Most regex patterns that purport to parse emails really don't work on many rfc compliant email addresses.
    The correct way is to validate it by verifying the different parts using tokenisation, but this is obviously not trivial. In additon, with domains in foreign languages (punycode encoded or not) and unicode user parts it becomes very complex to do it yourself... just find a good library instead.

  • @alexgghlebg5375
    @alexgghlebg5375 4 หลายเดือนก่อน +3

    As someone who learned with C and then C++, I honestly think one-liners are bad code. Even my programming Python teacher in French college always forced us to use one-liners with lambda whenever possible...
    It's true that code can be written faster, but readability takes a hit. This is just my opinion, but code that is not clear as day to read is not good code. It needs to be rethought how this algorithm was implemented, even if the final code is 100 or 200 lines more than if you use one-liners.

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

      I agree with you for the most part, but like he said, readability is pretty subjective. I find the decision to use one-liners to be best left up to the time complexity reduction over the readibility index, like with comprehensions.

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

      ​@@squishy-tomatowym by you can't name your function

  • @rodrigoqteixeira
    @rodrigoqteixeira 4 หลายเดือนก่อน +18

    That "noooo" was so unexpected.

  • @moorsyjam
    @moorsyjam 4 หลายเดือนก่อน +7

    An old one-liner I used to use for ternary operators was
    ("False text", "True text")[condition]
    and I wrote some truly monstrous nested nonsense.

    • @Russet_Mantle
      @Russet_Mantle 4 หลายเดือนก่อน +2

      using boolean as index is quite clever, just not sure if it's any faster than a simple if else block

    • @largewallofbeans9812
      @largewallofbeans9812 4 หลายเดือนก่อน +1

      @@Russet_Mantle it's probably slower than an ifelse, as it has to construct a tuple.

    • @moorsyjam
      @moorsyjam 4 หลายเดือนก่อน +2

      @@Russet_Mantle It's definitely slower. If, say, "False text" was an expression of some kind, the one liner would have to evaluate it even if it's not used.

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

      @@moorsyjam True. Thanks for the replies!

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

      clever is not a compliment in python. But if you must:
      {False: "F", True: "T"}[bool(condition)] is better,

  • @ShunyValdez
    @ShunyValdez 3 หลายเดือนก่อน +2

    TIL that you can call a lambda's variable function inside the same lambda's function. Neat.

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

      I think it's working only because of the if statement though so be careful

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

    flatten with level control: -> list
    flatten = lambda obj, level=-1: sum((flatten(sub, level - 1) if level != 0 and isinstance(sub, (list, tuple)) else [sub] for sub in obj), [])
    flatten(obj) -> entirely flattened
    flatten(obj, level = 1) flattened to level
    t = (1, (2, (3, (4, 5), 6), 7), (8, 9))
    flatten(t) -> [1, 2, 3, 4, 5, 6, 7, 8, 9]
    flatten(t, 1) -> [1, 2, (3, (4, 5), 6), 7, 8, 9]
    flatten(t, 2) -> [1, 2, 3, (4, 5), 6, 7, 8, 9]
    flatten(t, 3) -> [1, 2, 3, 4, 5, 6, 7, 8, 9]

  • @nashiki4792
    @nashiki4792 4 หลายเดือนก่อน +1

    What is the plug-in that you use for checking type hints?

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

    4:20 Why do you use Callable (capitalized)? Why is it better to annotate everything using types from the typing module? Because I use plain build-in type classes (str, int, bool etc.), and it all works as expected. (I use python 3.12.1)

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

    Don't know people who shout out "pythonic pythonic pythonic" and leaves the if __name__ == '__main__' check and opt for the "NON PYTHONIC" main() function. Python always encourage self descriptive name. The function main means nothing and you loose control over all global variables and class instances. If you want to test your module use __name__ check, it will never execute on import. If you really don't want your program to not have access to global space then give the method a self descriptive name instead of main().

  • @Fabian-ff4cq
    @Fabian-ff4cq 4 หลายเดือนก่อน +60

    the flatten example is not very readable. I‘d call it bad code.

    • @Sinke_100
      @Sinke_100 4 หลายเดือนก่อน +3

      I was acually most amazed with that one, even though I don't like reccursion

    • @rubenvanderark4960
      @rubenvanderark4960 4 หลายเดือนก่อน +15

      0:08

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

      ​@@rubenvanderark4960 if you have a clear indication of variable name, you don't need much readability in your function, especially for a small one like that. It's a beautiful piece of code

    • @Dunning_Kruger_Is__On_Youtube
      @Dunning_Kruger_Is__On_Youtube 4 หลายเดือนก่อน +21

      You must have missed the beginning of the video.

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

      @@Sinke_100 "reccccccursion"...kinda ironic.

  • @Libertarian1208
    @Libertarian1208 4 หลายเดือนก่อน +12

    Not relevant at this moment, but typing.Callable is deprecated (but will not be removed for a long time). The standard library docs use collections.abc.Callable for type annotations

    • @U53RN07F0UND
      @U53RN07F0UND 4 หลายเดือนก่อน +3

      Yeah, it's an odd design decision. I'd much rather all of my typings come from a single import, especially one I use as much as Callable. It's slightly obnoxious to have to `from this.that.here.there import thing` every time you want to import a type.

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

      Yeah and callable isn't even a collection, and other stuff like optional is still in typing

  • @xXherbal1stXx
    @xXherbal1stXx 18 วันที่ผ่านมา

    i always use this to print out list contents to the console if i want to check if everything is ok:
    print(*list, sep='
    ')

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

    You know... readability is exactly why all that typing frustrates me.

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

    Reversing and printing containts of an object
    print(*reversed(phrase),sep="")

  • @juxyper
    @juxyper 4 หลายเดือนก่อน +1

    The flatten example could very well easily extend to other iterables as well by passing an array of types instead of list maybe. Though it is painfully unreadable, but at the same time you just call it as a function that does things so why not

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

    I work with databases a lot and I do a lot of data manipulation. Do you have any lessons for that?
    I like continuation.

  • @GaloisFan
    @GaloisFan 3 หลายเดือนก่อน +1

    The greatest type annotation paradigm herald in the universe

  • @juschu85
    @juschu85 4 หลายเดือนก่อน +2

    Python is such an intuitive language but I think conditional expressions are much more intuitive in other languages. Basically any other language I know uses [condition] [true case] [false case] while Python uses [true case] [condition] [false case]. That's just weird. Full if blocks also have the condition first.

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

      It's weird but syntactically sensible. When you are assigning things through a condition you kind of want to first of all see the typical result rather than the conditional statement itself. Your explanation is also valid, it's just how it is anyway

    • @Russet_Mantle
      @Russet_Mantle 4 หลายเดือนก่อน +3

      Also in cases like "return a if condition else b", to make it parallel the syntax of full if blocks it really should be "return a if condition else return b" (more readable too). But I guess we can't have two return keywords in a single line

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

      It has to do with the "colon". Your preferred format would be:
      >>>if x: T else F
      so we have a statement with a colon and if it worked, hidden cyclomatic complexity of 2
      >>>T if x else F
      is just an expression, with unit cyclomatic complexity.
      Python doesn't mix statements and expressions, which is why Guido said there will never be a ++n, n++ style operator in python. The walrus operator is really not pythonic. ofc, neither are type annotations.

  • @bobby_ridge
    @bobby_ridge 4 หลายเดือนก่อน +1

    I've been waiting for a new video for a long time) tell me, pls, how to resize the window in paycharm?(8:28)

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

    True if Expr else False is equivalent to just Expr

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

    Christ, you weren't kidding in that disclaimer 😅 Pretty impressive how much Python can do in only a single line though!

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

      I mean theoretically I think you can write a lot more, if not an entire program, on a single line, but keeping it within the 80 char line limit was my goal ahah

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

    I like the output of the short one liner import this :)

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

    Creating a lambda function and assigning it directly to a variable is considered bad practice.

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

      You want it in nested for loop perhaps? or inside another lambda?

  • @swolekhine
    @swolekhine 4 หลายเดือนก่อน +1

    one-liner comment for the algorithm

  • @arb6t9
    @arb6t9 4 หลายเดือนก่อน +1

    Thanks Sensei 😀

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

    To get around the error in the flatten example you can do it the "old" way:
    from Typing import Any, TypeAlias
    new_type: TypeAlias = list[Any]
    # Passes type check
    var1: new_type = ["anything", 123, True]
    # Fails type check
    var2: new_type = {"hello", 321, False}
    This should still work in any version of python after 3.10, though it is officially depreciated after 3.12 in favor of the method you used in the video... Red lines bother me though, so :p

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

    I appreciate that in the vast majority of your videos you use only pure Python. However, there is one third-party library I will always require, and that is regex. I don't know why, but Python has the absolute WORST flavor of regex known to man (i.e. re). The regex library fixes all of the flaws inherent in the default re library, and is on par, if not better than the ecma (JS) and pearl implementations.

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

    5:54 You can use Forward References (the name of the type as a string) to annotate recursive types. In this example, it would be:
    type Nested = list[Union[int, 'Nested']]
    You can then annotate nested_list with the Nested type.
    Using Union instead of the pipe (|) is needed because using pipe on a string results in a type error.

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

    Assigning lambdas is discouraged and even disallowed by most linters. The flatten example does not work on generic sequences, while it should.

  • @mebbaker42
    @mebbaker42 4 หลายเดือนก่อน +1

    These are fun but you’re right on readability!
    Curious as to where you map your __main__ shortcut. Can you please share?

    • @Indently
      @Indently  4 หลายเดือนก่อน +3

      In PyCharm they're called Live Templates, which can be found under the Editor tab in settings. Then just go to Python and have fun creating them :)

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

      @@Indently Awesome. Thanks so much! I get serious shortcut envy when watching your videos! Keep em coming!

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

    What is the extension to put all the space at the right place

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

      Just press tab

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

    I remember seeing a reflex match phase that is over 200 characters long to be able to match 99.999% of email addresses due to the sheer complexity of getting all permutations of emails

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

    Regarding the reversal of iterables. How does that actually work? My understanding of Iterables always was, that they do not need to terminate. Does the reversal of a non-terminating iterable give you another iterable, that never yields when as you call next on it?

  • @mohanasundaram1686
    @mohanasundaram1686 4 หลายเดือนก่อน +1

    As always .like your videos

  • @NeoZondix
    @NeoZondix 4 หลายเดือนก่อน +1

    Github link gives 404

    • @Indently
      @Indently  4 หลายเดือนก่อน +1

      Thanks, I have fixed it!

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

    Why python users regard the shorter as the better code? It's sometimes really useless and has bad readability.

  • @bobdeadbeef
    @bobdeadbeef 4 หลายเดือนก่อน +1

    These are por uses of lambda. Python's lambda is limited in both arguments and body, and leads to the need to use Callable on the variable. Just use def!

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

      Yeah, I was told that they are called anonymous functions for a reason, and that if I needed to name it, I should just write a regular function. I will make a named lambdas every once and a while though. I pretty much only every use lambdas as sort keys or in regexes.

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

      lambda are indeed for in-line work: filter(lambda.., ....), map, reduce, ....

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

      It's already a well known bad practice to assign a lambda (anonymous function) to a variable, this defeats the purpose of using an anonymous function

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

      @@ahmedkhedr2631 The situation is different in JavaScript & TypeScript! It's partly a historical glitch. Functions defined with 'function'-anonymous or not- have different behavior wrt the scoping of 'this', while the closer analogy to lambda (arrow functions) have the more modern behavior, but do not themselves have names. But if initially assigned to a variable, they their name from the variable, so they are not really anonymous in that context.

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

      @@bobdeadbeef Thank you for that info, I thought Python's conventions regarding lamdas were universal across all languages but seems not

  • @juliusfucik4011
    @juliusfucik4011 4 หลายเดือนก่อน +3

    I appreciate most of the examples. The flatten example is okay; completely unreadable code. I would write a separate normal function to do this and write explanation im the comments.
    But in reality, if you end up with that many nested lists, your problem is in data design and management. I would go back and look into that such that a flatten function is not even needed.

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

      and a decent implementation uses yield from, an uncommon but powerful python construction:
      def flat(cont):
      for item in cont:
      try:
      len(item):
      except TypeError:
      yield item
      else:
      yield from flat(item)
      The worst part was when he said that lists have a "dimension", that is a priori the wrong data model.....but sometimes, you don't write you input format, you're stuck with it....CCSDS I'm looking at you.....

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

    my favorite one-liner won't even fit in this comment section 😂

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

    7:14 Why dont you use Ctrl to move faster? :)

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

    Can I make this?
    if years_old > 25:
    info = "You can vote"
    elif years_old > 18:
    info = "You can drink beer"
    else:
    info = "You are kid"

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

      info = "You can vote" if years_old > 25 else ("You can drink beer" if years_old > 18 else "You are kid")

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

      @@EdgarVerdi thanks

  • @SRIKRISHNAV-o5b
    @SRIKRISHNAV-o5b 4 หลายเดือนก่อน

    Why you do try videos on New Father 😂 of python.... .Mojo🔥

  • @godwinv4838
    @godwinv4838 4 หลายเดือนก่อน +1

    hello sir

    • @Indently
      @Indently  4 หลายเดือนก่อน +1

      hello

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

    lmao, idk, что python может использовать лямбду для выполнения рекурсии

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

    is it too early that i cant watch in full quality

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

      Apparently it says it will be available in 4K in 70 minutes, maybe they have a new system and have slowed down the upload speeds.

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

    Do you know how the type annotations work with numpy arrays? I read the numpy documentations but I don't think I understood it correctly (exemple in replies)

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

      def f(a: float) -> float:
      ...
      arr: numpy.ndarray = ...
      print(f(arr[3]))
      PyCharm tells me that the function f accepts only floats but I gave it a numpy array instead (it runs correctly)

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

      ​@@laytonjr6601Type annotations in Python have no effect at runtime

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

      Try google

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

      @@laytonjr6601 If I remember correctly, numpy array elements are lower dimention arrays. Eg 1D array will have 0D elements at least for type annotations. Also a tip, for less than 1000 elements, core python works faster than numpy unless you're using numba.

  • @knghtbrd
    @knghtbrd 4 หลายเดือนก่อน +1

    Been watching for awhile now, and I've got to recommend Indently's courses, despite not having taken any of them (yet). Federico understands the material and presents it very well. Not only that, he's demonstrated that he's picking up new techniques and, very importantly, he leaves in his mistakes. Yes, those are both good things, because you're going to make the same kinds of mistakes (we all do), and because Guido himself doesn't know all the ways Python can be used creatively by devs. These things are why you have to learn by doing, and keep your mind open to learning new things as you go.

  • @asboxi
    @asboxi 4 หลายเดือนก่อน +5

    I would like to remark that the elvis solution, always execute the first part before the if. first_element = array[0] if len(array) > 0 else None (this could fail if array == [])

    • @RadChromeDude
      @RadChromeDude 4 หลายเดือนก่อน +1

      even better
      first_element = array[0] if array else None

    • @DrDeuteron
      @DrDeuteron 4 หลายเดือนก่อน +1

      @@RadChromeDude that works with array.array from the standard library, but will throw a ValueError for a numpy.ndarray.

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

    Here's my one liner for creating a cyclomatic polynomial class instance (in 2x):
    cyclomatic = type('CyclotomicPolynomial', (object,),
    {'__call__': lambda self, n, x: self[n](x),
    '__getitem__’: lambda self, n:
    scipy.poly1d(
    map(
    scipy.real,
    reduce(
    scipy.polymul,
    [
    scipy.poly1d(
    [1,0]
    )-
    scipy.exp(1j*(2*scipy.pi/n))**k
    for k in
    filter(
    lambda a:
    (
    2*sum(
    [
    (k*n//a) for k in range(1,a)
    ]
    )+a+n-a*n)==1,
    range(1,n+1)
    )
    ]
    )
    )
    )
    }
    )()