Top 10 Python One Liners YOU MUST KNOW!

แชร์
ฝัง
  • เผยแพร่เมื่อ 16 ก.ย. 2024
  • Top 10 Python One Liners YOU MUST KNOW!
    Find Python jobs: pythonengineer...
    Get my Free NumPy Handbook:
    www.python-eng...
    ✅ Write cleaner code with Sourcery, instant refactoring suggestions in VS Code & PyCharm: sourcery.ai/?u... *
    ⭐ Join Our Discord : / discord
    📓 ML Notebooks available on Patreon:
    / patrickloeber
    If you enjoyed this video, please subscribe to the channel:
    ▶️ : / @patloeber
    ~~~~~~~~~~~~~~~ CONNECT ~~~~~~~~~~~~~~~
    🖥️ Website: www.python-eng...
    🐦 Twitter - / patloeber
    ✉️ Newsletter - www.python-eng...
    📸 Instagram - / patloeber
    🦾 Discord: / discord
    ▶️ Subscribe: / @patloeber
    ~~~~~~~~~~~~~~ SUPPORT ME ~~~~~~~~~~~~~~
    🅿 Patreon - / patrickloeber
    #Python
    ----------------------------------------------------------------------------------------------------------
    * This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you so much for the support! 🙏

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

  • @lawrencedoliveiro9104
    @lawrencedoliveiro9104 ปีที่แล้ว +232

    Here’s one: deleting an entry from a dictionary, but only if it exists. Because
    del dict[key]
    will raise KeyError if there is no such entry. So you have to do an explicit check first, the long way:
    if key in dict :
    del dict[key]
    ♯end if
    but there is a shorter way:
    dict.pop(key, None)

    • @318th
      @318th ปีที่แล้ว +6

      Thats a clever one

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

      You can use the dict.get(key)
      If the key doesn't exist it will return None so the code will be like this
      If dict.get(key) is not None:
      del dict[key]

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

      @@ghaythghannouchi3427 Or "del dict[key] if dict.get(key) else None"

  • @NikoKun
    @NikoKun ปีที่แล้ว +72

    A couple of my favorite one-liners:
    # Remove whatever punctuation you want from an input string:
    outputStr = "".join(ch for ch in inputStr if ch not in ",.?!'")
    # Return the Ordinal Suffix for day of the month: 1st, 2nd, 3rd, 4th, etc.
    def ordsuf(day): return ["","st","nd","rd"][day%10] if day%10 in [1,2,3] and day not in [11,12,13] else "th"
    # alternative that returns both number and suffix together, takes string, gives string:
    def orday(day): return day+'th' if int(day) in [11,12,13] else day+{1:'st',2:'nd',3:'rd'}.get(int(day)%10,'th')

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

      Could you please explain the second one? I'm unable to get it

    • @NikoKun
      @NikoKun ปีที่แล้ว +13

      @@jatindua5866 Sure, that one is a bit tricky to explain, but I'll try. It defines a function called ordinal, which when provided a integer, usually a day from 1-31, the function returns a string of either "st", "nd", "rd", or "th". The part after return is a list containing those, but in a specific order, because we then use [day%10] as an index to determine which of those 4 strings is returned. %10 divides the number by 10, but ignores the result and gets the remainder left over instead, so 23 just becomes 3. The next part, if day%10 in [1,2,3] ensures that list gets used for results 1, 2 and 3. Then "and day not in [11,12,13] excludes those specific numbers because they're exceptions to the rule that use "th" instead. Everything else also just uses "th". Hope that all makes sense..
      Functionally, this was just the shortest version, I've also used several variations of that function, depending on whether I want to input an int or a str, or whether I want the output string to include the number first, or not. heh
      Here's a slightly longer version, more formally written, that takes a string and outputs a string with the number and suffix already together. Works well with time.strftime("%e"):
      def ordinalday(day: str) -> str:
      return day+['','st','nd','rd'][int(day)%10] if int(day)%10 in [1,2,3] and day not in ['11','12','13'] else day+'th'
      And of course these don't have to be used with days, that's just the most likely use, they can also works with other numbers, like 42nd. ;)

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

      @@NikoKun Thank you for your time and such a clear explanation.
      Have a great day ahead!

    • @Eknoma
      @Eknoma ปีที่แล้ว +8

      This is why oneliners are bad, it would have been much much cleaner code if you just allowed more vertical space, for example:
      ```python
      def ordsuf(day):
      if 0 < day%10 3 or day in [11, 12, 13]:
      return "th"
      return ("th", "st", "nd", "rd")[day%10]
      ```

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

      @@Eknoma Or just import datetime & co. 😎
      2:16 AM
      11/22/2022

  • @stuartberg8030
    @stuartberg8030 ปีที่แล้ว +47

    I consider myself very proficient in Python, but it had never occurred to me to use #4: print(*data). I will be using that very frequently from now on.

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

      a

  • @dewaard3301
    @dewaard3301 ปีที่แล้ว +12

    Not a specific oneliner, but the fact that despite its reliance on indentation you can turn any python script into a oneliner is very helpful when sharing code snippets for commandline execution.

  • @demitri_t
    @demitri_t ปีที่แล้ว +11

    0:42 Important to know: the list comprehension is also MUCH faster faster than iteration approach.

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

    1:57 If I remember correctly, you can also provide an argument to the print() function called 'sep', this will be the string that separates the elements (it's a space by default)
    So, for example:
    print(*data, sep='; ')
    Will print
    0; 1; 2; 3; 4; 5

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

      Instead of sep I'll use end =';'

    • @sobbski2672
      @sobbski2672 10 หลายเดือนก่อน +1

      ​@@jaylooppworld381that would add a ";" after your last element too. While sep only adds the separation between elements

  • @kidsfree6615
    @kidsfree6615 ปีที่แล้ว +61

    WARNING: ⚠⚠⚠ This video has BAD ADVICE
    To read a file please use a "with" statement as such:
    with open(filename,"r") as file:
    arr = [line.strip() for line in file]
    "with" statements will automatically close the file if there is an exception or when the "with" block is done.
    Otherwise the file may not be closed right away and can cause weirdness.

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

      Indeed. But it's still a good one-liner if it's used through a command line :)

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

      @@demitri_t wdym command line?

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

      @@gigachad8810 python3 -c 'print(one-liner)'

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

      @@demitri_t bro why would you use python to open files in a cli. just use cat or echo with a pipe. also, that doesnt fix the issue with that one liner outside of clis

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

      @@gigachad8810 There are things difficult to do in bash. But the reason why I mentioned it is at 2:22 ;)

  • @Soul-Burn
    @Soul-Burn ปีที่แล้ว +9

    For #6 Another alternative is to use reversed(x), which makes an iterator rather that a list, so it's useful when iterating it.
    For #8 I'd recommend using a list comprehension instead my_list = [int(x) for x in user_input.split()] , as it's more readable.
    For #9 It's a bad practice to use open on a single line rather than using with open(x). Also, strip will remove starting and ending whitespace which is not what you always want.

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

      It's all true.
      A small note for #8. Indeed, a PEP recommends the list comprehension over the map call. But the map call is less verbose and more functional oriented ;)

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

    return a or b
    Will return b if a is falsy, else a (this helps if you want a default value b in case a == None or something similar).

  • @dvdraymond
    @dvdraymond ปีที่แล้ว +19

    Might fall into the realm of one-liners, but one tip I have is to remember that booleans are a sub class of integer, and thus can be used as the index of a list/tuple, etc.
    So for your #3 example, you could also write it as
    var = (99, 42)[3 > 2]
    I've used that for example when I'm writing a csv, and don't want to used the long "True" and "False" text representations.
    boolAsText = "NY"[boolValue]
    boolAsText = ("No", "Yes")[boolValue]
    etc.
    Maybe someone could come up with a better real world use of that.

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

      I often use this when I have to return a specific value in the case the condition it's true or when the condition is false

  • @manojm9084
    @manojm9084 ปีที่แล้ว +12

    Waking up in the morning seeing this as the first video with so much useful information. How can a day be more better than this .
    Thank you 😊

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

      Glad you enjoyed it!

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

      Morning sex?

    • @RyanClark-gr9yb
      @RyanClark-gr9yb ปีที่แล้ว

      @@patloeber You forgot that you can simultaneously step through two iterables in a single for loop:
      for (name,adress) in zip(names, adresses):
      print(name, address)

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

      @@RyanClark-gr9yb The correct way for a video about One Liners would be: print([f"{name}, {address}" for name, address in zip(names, addresses)])

  • @michaelrogovin
    @michaelrogovin ปีที่แล้ว +153

    #9 - you need an additional line to close the file

    • @ansonmiu8464
      @ansonmiu8464 ปีที่แล้ว +10

      Could use pathlib.Path - `pathlib.Path(filename).read_text().splitlines()`

    • @lokeshkalamalla
      @lokeshkalamalla ปีที่แล้ว +8

      Will 'with' work?

    • @dibbyo456
      @dibbyo456 ปีที่แล้ว +20

      @@lokeshkalamalla if you use use “with” you don’t need to close it, because it closes itself.

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

      Thats what i immediately thought too

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

      Not true IMHO. The file will be closed when the file object runs out of scope, which is at the end of the line.

  • @re.liable
    @re.liable ปีที่แล้ว +3

    For 4: The `end` argument can be a `
    ` to print the items in their own lines. I know the tip title says "without new lines" but I use both very often. There's also the `str.join` approach, e.g. `' '.join(data)` but that requires the items to be cast as strings first, if they're not already. Very handy if the joined string is to be used in another area however (i.e. not to be printed)
    I am really fond of that one-liner as it's the one that made unpacking click for me. I also use the "equivalent" of it in JS a lot (spread and rest)

  • @DecimasoN
    @DecimasoN ปีที่แล้ว +11

    You could also just use list comp for number 8 too [int(i) for i in a.split()]

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

      I think map is faster.

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

      @@mienislav only by a microscopically small amount, e.g. 1usec.
      This is reversed when it requires a lambda.

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

      @@DecimasoN yeah, so it is (marginally) faster, AND more readable. That's a win-win

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

      @@Eknoma I prefer the comprehension here bc you have to remember to use both map and then convert back to a list in the other one. The comprehension is easier to read

  • @studyingasyouwere
    @studyingasyouwere ปีที่แล้ว +8

    Always an insightful video. These types of videos consistently inspire me to post coding content myself! Thank you :)

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

    the list(map(int, ...)) is fine but I prefer [int(x) for x in ] for readability.

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

    gr8 video :
    btw you can use if statments without using them :
    print(["hello","world"][1>2])

  • @rgvn8406
    @rgvn8406 ปีที่แล้ว +8

    Thanks for the video, I just wanted to add this :)
    # traditional function with def
    ```
    def sum(a, b):
    return a + b
    ```
    # lambda function
    ``` sum = lambda x, y: x + y
    ```

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

      Or just use operator.add.

    • @Soul-Burn
      @Soul-Burn ปีที่แล้ว

      The function one is 99% of the times more readable than using a lambda.
      Only use a lambda when it's inline when e.g. calling a function. For example sorted(a, key=lambda x: x[0]) .

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

    4:08 I would suggest pathlib for reading and writing files these days.
    from pathlib import Path; names = Path(“names.txt”).read_text().split()

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

      Why is this better than with open?

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

      @@moahmadi22 read_text closes your file

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

    You should be careful when using that reversing trick, because it creates a copy of your list (at least for the standard List; I think numpy arrays don't do that). You generally want to use `reversed()` instead, which won't copy.
    Also: NEVER use a bare `open()`. Only use it in a with statement.

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

    #8. For better clarity, we can use list comprehensions like this
    a = '1 3 5 6'
    b = a.split()
    c = [int(i) for i in b]
    print(c)

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

      Memory efficiency
      Using gerator objects
      a = '1 3 5 6'
      b = a.split()
      c = list(int(i) for i in b)
      print(c)

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

    checking zero on None value with 'or'
    if not var:
    var = 'something'
    you can use:
    var = var or 'something'
    usefull when you expect a certain type and wanna rule out None:
    (d or {}).get('element')
    (L or [None])[0]

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

    A lot of people have pointed out that in 8, you could use a list comp even though map is shorter, more clear, and faster. The real issue it that you gave no safe catch for if the data could not be converted to integers.

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

      I doubt the map is faster. Is it really so? The interpreter should convert a comprehension into a single C call as well as it does with a map call.

  • @5ucur
    @5ucur ปีที่แล้ว

    In list comprehension, you can even use else, but you have to put the if-else before the for, like so:
    a = [n if n % 2 else -n for n in some_list]
    This will result in a list like [1, -2, 3, -4, 5], from some_list as [1, 2, 3, 4, 5].
    And you can do comprehension with other types like dicts too!

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

    Thank you, I love you bc I learn good tricks from you bro. Waves from Bolivia.

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

    I would include dict comprehension right after list comprehension.

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

    func=lambda x : x+1
    One liner for a function

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

    The multiple variable assignments ie (a, b = b, a) blew my minds a few weeks ago coming from other languages so handy

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

    He Pat, here after a long time. Just wanna let you know that I love your videos. Keep on making the good stuff.

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

    Please do more videos like this. Kind of refresher

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

    4:06 The "r" mode is default, so ', "r"' can be omitted :)

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

    If you want to ignore an exception,
    instead of try, except use supress exception

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

    Great video: A nice one-liner for CSV to JSON: python -c 'import csv, json, sys; print(json.dumps([dict(r) for r in csv.DictReader(sys.stdin)]))'

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

    The dict setdefault method is one that has come in handy for me more times than I can count.

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

    Very cool video. I've been using python, and am always looking to make life easier. Thanks!

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

    I know the point was the one-liner part of it, but opening a file in text mode without explicitly specifying the encoding just makes me shiver. You should never just assume the encoding will be the same as your system default, and if you're the one making the file you should always be able to know exactly what encoding your file is going to be in. Plus having the same script make different files when run on different systems is bad.

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

    Thanks so much for sharing! Greetings from Mexico!

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

    Amazing video man, cheers!

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

      Thank you! Cheers!

  • @traal
    @traal ปีที่แล้ว +8

    3:47 this should have been a list comprehension:
    my_list = [int(x) for x in user_input.split()]

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

      Using map is much more readable, and almost always faster

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

      @@Eknoma I doubt it's faster. The comprehension should basically be interpreted into a map call (in the lower C level). Otherwise PEP wouldn't recommend comprehensions over map calls.

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

      @@demitri_t It literally takes 2 seconds to check for yourself... why write a comment disregarding a result without even checking?
      On my system, list(map(int, s.split())) takes roughly 18% less time than [int(i) for i in s.split()]
      There would be literally no point in map if it was slower than a normal for loop... so obviously it has to be faster at some things

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

      @@Eknoma Yep, ~20% is expected for int(). But this is just because you tested the simplest case. Try e.g. lambda i: i * i instead. And I didn't tell anything about a normal loop. Did you test it as well?
      P.S. Indeed I didn't profile anything myself, I just found results in the stackoverflow :)

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

      @@demitri_t What are you talking about? Of course using a lambda adds performance overhead...
      So you first say you doubt using map for it's intended purpose is fast, and then you later say using it in a bad way is slow, what arr you getting at?

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

    For #2 why wouldn't you just use ... print([i*i for i in range(10) if i %2 ==0]) and then it truly is a one liner. Not declaring a variable and then printing the variable?

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

    #2 is also range(0,10,2), instead of the if statement

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

    Importing doesn't count. By that logic, I could make my own module with any function I want, and say that it is 1 line.
    Also, I could separate my entire program with semicolons and say it is one line, so that definitely doesn't count.

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

    Hi how to write to a file with oneliners? Thank you!

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

    Doest that 9th one liner requires to manually close the opened file? Cause with "with" you wouldn't need that. So does the list comprehension bypass the closing or not?

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

    dict2|=dict1 to merge two dictionaries in one line(3.9+)

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

    Unironically a fantastic resource to have.

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

    Intresting!
    Thanks

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

    "One liners"
    "Let's use the semicolon to make it technically a one liner"

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

    We can also use eval fn for str list 🙌🏾

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

      eval is EVIL

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

    I guess I'm an advanced Python developer because I've used all of those before. I consider myself to be a beginner to Python, so maybe I'm selling myself too short and should start applying for jobs.

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

    5th is not exactly a oneliner. There are two instructions of code. If we treat this as a one-liner, then we can wrap all Python codes in just one line adding everywhere semicolons.

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

    2:07 "add a semicolon to stay in the same line" that's one way to make a one liner 😂

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

    You forgot the conditional assignment it s a great technique to use

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

    There are 2 types of people that clicked this video...
    I am both

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

    is it possible to use print(*data) to print each value on a new line?

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

      One way to do that is print(*data, sep='
      ').
      After it unpacks the data, the items essentially become different params in the print() call and then you use sep='
      ' to insert a new line instead of the default space between each item.

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

    What version of python were you using here? 3.10 or 3.1?

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

    amazing work
    thank you so much.

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

    I usually like one liners, but sometimes i take it too far... like when i made a 200+ letter long one liner... since then i think again if it's worth

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

    Great tips, thanks ☺

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

    I always use this trick to print iterables, item by item in a single line:
    _ = [print(a) for a in iterable]

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

    can i use these one liners on a date

  • @Allen-by6ci
    @Allen-by6ci ปีที่แล้ว

    Really good video.. thanks!

  • @_Elvyra._
    @_Elvyra._ ปีที่แล้ว +2

    You just commited a crime by using semicolons in python

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

    Which theme are you using for your vscode?

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

    Good list. My only gripe is that ternaries are expressions, not statements!

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

      But assigning the ternary to a variable does make it a statement

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

      @@elhombreloco3680 True, but the ternary itself is still an expression, that's *why* you can assign its value to a variable

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

    you forgot the.. "subscribe" one liner :P

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

    Tmatrix = [list(i) for i in zip(*matrix)]

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

    wonderful gift.

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

    Great tips! Tqqqqqq

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

    2:13 Don’t you mean, the first day of the next year? So that on 31st December, it will return 1 day left, not 0 days left.

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

      nice catch, yeah I should probably not exclude New Year's Eve

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

    cool! thanks

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

    does 9. have an implicit context manager?

    • @MaxMustermann-on2gd
      @MaxMustermann-on2gd ปีที่แล้ว +2

      I was wondering as welll ..

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 ปีที่แล้ว +6

      Remember that CPython does reference counting, so objects are automatically disposed when their refcount goes to zero. For file objects, this means the file is automatically closed.
      I wouldn’t recommend relying on that for files open for writing, since then you might miss I/O errors because the volume is full etc. For files open readonly, I do this sort of thing all the time.

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

      @@lawrencedoliveiro9104 thank you

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

      Good question! Yes I agree with Lawrence. Python docs say "Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly)."
      So my one-liner is not best practice, but probably also doesn't do harm in this case...
      See docs: docs.python.org/3/reference/datamodel.html#index-2

    • @MaxMustermann-on2gd
      @MaxMustermann-on2gd ปีที่แล้ว

      @@patloeber thank you and @Lawrence ... Yes, i'd also argue that it isn't best practice, but interesting to know that cpython takes care of this, so from a technical perspective it is indeed "clean" code.

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

    #5 is actually cheating since you can write the whole core in one line using semicolon instead of a line break. But this video is full of good tips, thank you..

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

    Hi, do you have videos with regex module?

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

    This man is just 😎 😎 !

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

    Nice. I'm beginner and I didn't know any of them. Thanks. But what I don't like in your videos 📸....you are too fast for me 😂 I need to watch your videos many times to catch it 😉

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

    Is it all in the... timing?

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

    very fast paced. Wouldn't hurt to give the people a decent amount of time to read without rewinding the video.
    And since 1 and 7 are the same, its kinda cheated :D
    Otherwise, nice vid

  • @Nick-lc3ll
    @Nick-lc3ll ปีที่แล้ว

    so in 2 you show how to use list comps but in 8 you miss out on the most obvious use case of them? a list comp would look much nicer than a map here imo

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

    You're really good but a bit fast. Your presentation always moves quite fast. If you could adjust the speed a but that would allow me to follow you more easily.

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

    Pls anybody ans why if i write this code will return false
    A = 20
    A = int(A)
    Print(a is int)

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

      you are comparing value to a class, it will only return true in this case:
      print(type(a) is int)
      this is what you need to check if value is int:
      print(instance(a, int))

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

      @@bilaldz9304 Thanks sir

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

    A few of these remind me of excel formulae

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

    hi, does anyone know which extension for vscode he uses so his output updates as he types?😊

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

      Don't I dont know but you can us
      import os; os.system('cls')
      Put this code in the top level of you code and each time you run the code, the terminal will delete the Last output before the new output is shown in the terminal

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

    Helpful 🙏

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

      Glad you think so!

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

    Thanks

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

    Reading a file in one line isn't great practice. you do need to close the file when you are done

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

    Thank you

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

      You're welcome

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

    excellent!

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

    Using a semi colon in number five is both cheating and disgusting. Assuming datetime was already imported on a different line however, it is fine

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

    You are the best ;)

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

    This is a real deal!

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

    useful

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

    ternary == danger

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

    value = not value

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

    pass

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

    I've seen the tip with the variable swapping quite a few times, but it's the most useless thing ever. Never in my 5 years of programming have I had to use this. It reduces readability and does nothing useful. Please give me one simple example where you would actually use this.

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

    Here is the true oneline killers that you should never use if you don't wanna have problems with you supervisor
    #1 Lambda x: [sys.stdout.write(line) for line in x]
    #2 lambda x: list(map(sys.stdout.write, x))

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

    one-liners are not cool and against PEP8

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

    I know them all but anyway I enjoy when I watching it 😂😂
    Thanks ♥♥

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

    8/10 👌