Python tricks thread

What python tricks do you like the most?
Mine is
z = (a, b)[x > y]
It assigns z to a if the condition x > y is false

Homeless People Are Sexy Shirt $21.68

Nothing Ever Happens Shirt $21.68

Homeless People Are Sexy Shirt $21.68

  1. 2 years ago
    Anonymous

    Nice trick anon but isn't that also possible with ternary operators?

    • 2 years ago
      Anonymous

      Its because Python evaluates "False" as 0 when accessing a tuple

      Why would anyone use this?

      I guess it a neat trick for code golfing.

      • 2 years ago
        Anonymous

        Yup, nvm
        z = (a, b, c)[True + 1]
        based, checked and True + 1, returns the 3d element.

      • 2 years ago
        Anonymous

        Speaking of code golfing here's how you import inline.
        list(__import__('itertools').product(range(10), repeat=2))

        • 2 years ago
          Anonymous

          That's kind of wild anon.

    • 2 years ago
      Anonymous

      Does Python have ternary operator?

      • 2 years ago
        Anonymous

        yeah but it's written more unusually than most languages
        result = x if a > b else y

  2. 2 years ago
    Anonymous

    z = b if x > y else a

    • 2 years ago
      Anonymous

      This > Op

      It's different to the op's trick in that you evaluate both a and b no matter the condition, but you only evaluate a or b in your if else one liner

  3. 2 years ago
    Anonymous

    z = (a, b)[(not x < y) if x > y else 1]

  4. 2 years ago
    Anonymous

    >It assigns z to a
    it assigns a to z

  5. 2 years ago
    Anonymous

    z = (a, b, c)[(not x < y if x > y else 1) if not x == y else 2]

  6. 2 years ago
    Anonymous

    for a, b in zip(x, x[:1]):
    ... #this is also a trick, ellipsis is a valid placeholder nowadays

    • 2 years ago
      Anonymous

      sorry should be x[1:]

  7. 2 years ago
    Anonymous

    Python 3.8.10 (default, Mar 15 2022, 12:22:08)
    [GCC 9.4.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> x = range(3); y = range(3)
    >>> [(l,r) for l in x for r in y]
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
    >>> eval("[(l,r) for l in x for r in y]", {"x": x, "y": y}, {})
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
    >>> eval("[(l,r) for l in x for r in y]", {}, {"x": x, "y": y})
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<string>", line 1, in <module>
    File "<string>", line 1, in <listcomp>
    NameError: name 'y' is not defined
    >>>

    I haven't checked 3.10, but I would be surprised if it's not broken there too.

    In contrast:
    Python 2.7.18 (default, Mar 8 2021, 13:02:45)
    [GCC 9.3.0] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> x = range(3); y = range(3)
    >>> eval("[(l,r) for l in x for r in y]", {}, {"x": x, "y": y})
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

  8. 2 years ago
    Anonymous

    >le python is le simple language
    >only one way to do things
    Explain yourselves pythoBlack folk.

    • 2 years ago
      Anonymous

      >le putting words into people's mouths

      • 2 years ago
        Anonymous

        >Hasn’t heard of the zen of python

        • 2 years ago
          Anonymous

          Im aware of PEP20 and many of the autistic conventions people on Stackoverflow like to peddle but I don't think I've ever seen people follow them to the letter ever.

  9. 2 years ago
    Anonymous

    I wonder how long before I can be a pro-python ML coder

  10. 2 years ago
    Anonymous

    readable code > "le tricks"

    • 2 years ago
      Anonymous

      I think OP just posted it as a nice tidbit of info. Also its beneficial to know that Python indeed does convert booleans to integers at times.

      • 2 years ago
        Anonymous

        >Python indeed does convert booleans to integers at times
        To be more precise, booleans ARE integers in Python:
        >>> isinstance(False, int)
        True
        >>> False == 0
        True
        This was originally for compatibility with the existing practice of putting "False = 0" and "True = 1" at the top of the file, back before Python had bools. This is also why you can assign to them in Python 2 but not in Python 3:
        $ python2 -c 'False = 0; print(False)'
        0
        $ python3 -c 'False = 0; print(False)'
        File "<string>", line 1
        SyntaxError: cannot assign to False
        There's even code in the standard library that still uses 0/1 instead of False/True. This is from urllib/request.py.

        • 2 years ago
          Anonymous

          >To be more precise, booleans ARE integers in Python
          Useful if you want to count how many items in array fulfill a condition.
          >>> sum(i >= 10 for i in range(20))
          10

      • 2 years ago
        Anonymous

        >Python indeed does convert booleans to integers at times.
        Python bools subclass int, so you can do strange things like
        In: sum([True, True, False, True, False])
        out: 3

        • 2 years ago
          Anonymous

          He is clearly summing all 3 Trues. Seems like the appropriate response.

          • 2 years ago
            Anonymous

            If it has to do something then it might as well do that, but a TypeError might be better.

      • 2 years ago
        Anonymous

        >Python indeed does convert booleans to integers at times.
        Python bools subclass int, so you can do strange things like
        In: sum([True, True, False, True, False])
        out: 3

        for n in range(1, 101):
        print({
        (0, 0): n,
        (1, 0): 'Fizz',
        (0, 1): 'Buzz',
        (1, 1): 'FizzBuzz'
        }[n % 3 == 0, n % 5 == 0])

        • 2 years ago
          Anonymous

          Beautiful

          • 2 years ago
            Anonymous

            Say you have a list like this you want to split into a dictionary:
            some_list = [“key1=abcd”, “key2=efgh”, “key3=ijkl”]

            dict = {key: value for key, value in map(lambda i: i.split('='), some_list)}

          • 2 years ago
            Anonymous

            Shit meant to tag OP

            https://i.imgur.com/GSRx7C4.png

            What python tricks do you like the most?
            Mine is
            z = (a, b)[x > y]
            It assigns z to a if the condition x > y is false

          • 2 years ago
            Anonymous

            You can do the same thing without the map by using the dict constructor

            d = dict(I.split(“=“) for I in some_list)

        • 2 years ago
          Anonymous

          >look at this
          >look at my FizzBuzz
          >feel moronic

          for i in range (1,101):
          if i%3==0 and i%5==0:
          print('FizzBuzz')
          elif i%3==0:
          print('Fizz')
          elif i%5==0:
          print('Buzz')
          else:
          print(i)
          [code]

          I'll never code

          • 2 years ago
            Anonymous

            It's not really that hard, moron. You should learn an easier language, I suggest Scratch.

          • 2 years ago
            Anonymous

            I'm trying to learn by myself with courses and so, but I don't think 'm doing pretty well.
            I'll probably go for C next, maybe it will help gettin a solid foundation.

          • 2 years ago
            Anonymous

            Your way is how someone normally will write it.
            Another shitty way:
            print(*('Fizz'*(i%3==0)+'Buzz'*(i%5==0) or i for i in range(1,101)), sep='n')

            Showcasing print function (py3) strength over print statement (py2), iterator unpacking operator * (e.g. [*it] is list(it)), multiplying with false (0) a string returns empty string, and that empty strings are considered false (e.g. '' or 2 returns 2) although they aren't equivalent to false ('' == False is False).

  11. 2 years ago
    Anonymous

    os.execvp('guile', ['guile'])

  12. 2 years ago
    Anonymous

    My only trick is using sets, sets are fast, fast sets make python fast, fast fast gotta go fast.

    • 2 years ago
      Anonymous

      you mean tuples right?

      • 2 years ago
        Anonymous

        Sets can't you read motherfricker, sets!

        • 2 years ago
          Anonymous

          oh you're moronic

          • 2 years ago
            Anonymous

            sets are not tuples
            idk what you're whining about

          • 2 years ago
            Anonymous

            where would you replace a data structure with sets where it is not already a set?

          • 2 years ago
            Anonymous

            Classic examples would be if you want to test if two or more iterables are disjoint or if you are using the in operator on a big iterable

    • 2 years ago
      Anonymous

      Sets are the slowest container type to construct, but are fast for doing membership test and disjoint tests

    • 2 years ago
      Anonymous

      >My only trick is using sets, sets are fast, fast sets make python fast, fast fast gotta go fast.
      yeah, I use sets a ton in my code. they're really useful. one annoying thing about Go is no native set type, even if it's easy to implement manually

      • 2 years ago
        Anonymous

        I try to use sets when semantically justified. i.e. a user is a member of a set of groups, and groups have sets of members. I've rarely regretted it.

      • 2 years ago
        Anonymous

        With the addition of generics, I'll bet that a set DS might be added to the stdlib.

  13. 2 years ago
    Anonymous

    My favorite python trick is installing Rust, it's just a simple:
    os.system("curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh")

    • 2 years ago
      Anonymous

      based and rust pilled.
      my trick is to just use starlark instead.

    • 2 years ago
      Anonymous

      ok, troony

  14. 2 years ago
    Anonymous

    Making a dict out of two iterables
    dict(zip(a, b))

    Provided the contents of them are hashable.I also have an affinity for the iterator protocol.

    • 2 years ago
      Anonymous

      based motherfricker here
      try:
      while True:
      current_instance = next(all_instances)
      self._attributes
      self.sort_iterators(current_instance)
      freq = self.join_single_instance(current_instance)
      entry = list(current_instance) + [freq]
      res_entries.append(entry)
      except StopIteration:
      pass

      recently shifted my entire codebase to work with iterators. works like a charm

  15. 2 years ago
    Anonymous

    teach me a trick to remove namespaces from element tags when using elementtree
    i used ET.register_namespace to regsiter all relevant namespaces, but they still appear in the tags, making it impossible to work with.

  16. 2 years ago
    Anonymous

    # naive swap
    a = 10
    b = 3

    temp = a
    a = b
    b = temp

    # pythonic swap
    a = 10
    b = 3

    a, b = b, a

    • 2 years ago
      Anonymous

      >pythonic
      This fricking buzzword makes me feel the same as Hispanic when they hear the word "latinx"

      • 2 years ago
        Anonymous

        maybe I'm just old (30), but I started using Python like 12 years ago and everyone said Pythonic all the time back then to mean "idiomatic and good" and I still use it, personally

      • 2 years ago
        Anonymous

        i mean you can say "more idiomatic python code" or "pythonic", kinda rolls off the tongue

  17. 2 years ago
    Anonymous

    i have actually used this in code I was paid to write
    from types import MethodType
    class A:
    def __init__(self):
    self.x = 20

    def func(self):
    print("my attr x is", self.x)

    def method_onetime_binder(obj, attrname):
    lastfunc = getattr(obj, attrname, None)

    def onetime(self):
    self.x -= 5
    print("this will only print once:", self.x)

    setattr(self, attrname, lastfunc)
    setattr(obj, attrname, MethodType(onetime, obj))

    a = A()
    a.func() # outputs "my attr x is 20"

    method_onetime_binder(a, "func")
    a.func() # outputs "this will only print once: 15"
    a.func() # outputs "my attr x is 15"
    a.func() # outputs "my attr x is 15"
    method_onetime_binder(a, "func")
    a.func() # outputs "this will only print once: 10"
    a.func() # outputs "my attr x is 10"

    • 2 years ago
      Anonymous

      Why?

  18. 2 years ago
    Anonymous

    Loops can have an "else" clause that gets executed if they dont "break" at some point
    https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

  19. 2 years ago
    Anonymous

    >What python tricks do you like the most?
    import pandas as pd

    • 2 years ago
      Anonymous

      learn how this ONE SIMPLE TRICK can get you a job IN LESS THAN TEN MINUTES

      • 2 years ago
        Anonymous

        Head over to my ABSOLUTE FINAL PYTHON ULTIMATE COURSE FOR 2022 | HINDI AND HURDU VEESION on Skillshare. Use the code 4CH to get a 0.00005% discount.

  20. 2 years ago
    Anonymous

    hello fellow pythonistas
    is it possible to achieve dot notation with python dictionaries?

    • 2 years ago
      Anonymous

      You can do this:
      class AttrDict(dict):
      def __getattr__(self, attr):
      try:
      return self[attr]
      except KeyError:
      raise AttributeError(attr)

      d = AttrDict({"x": 3})
      print(d.x)
      But you usually shouldn't, it looks misleading.

  21. 2 years ago
    Anonymous

    _ is placeholder for whatever is has been previously returned
    >>> f = lambda x: x**2
    >>> f(2)
    4
    >>> _**2
    16

    • 2 years ago
      Anonymous

      This is only true in the repl.

  22. 2 years ago
    Anonymous
    • 2 years ago
      Anonymous

      any also exists

      These become particularly interesting if you use comprehensions.
      nums = [3, 8, 7, 4]
      if all(n >= 5 for n in nums):
      ...

  23. 2 years ago
    Anonymous

    I also like filter and reduce, even though I've never used them in python code

  24. 2 years ago
    Anonymous

    for n in range(1, 51):
    match n % 3, n % 5:
    case 0, 0:
    print("FizzBuzz")
    case 0, _:
    print("Fizz")
    case _, 0:
    print("Buzz")
    case _, _:
    print(n)

  25. 2 years ago
    Anonymous

    install J: https://code.jsoftware.com/wiki/System/Installation

  26. 2 years ago
    Anonymous

    what do square brackets do

    • 2 years ago
      Anonymous

      indexing operator

  27. 2 years ago
    Anonymous

    the 'and' and 'or' operators work similar to lisp, in that they return the last value.
    >>l = [1,2,3]
    >>l and l[0] or 42
    1
    >>l = []
    >>l and l[0] or 42
    42

    it's almost an alternative to the ternary operator. your example could be written like this.
    z = x > y and a or b
    # z = a if x > y else b

    the semantics of what converts to boolean False make this a little sketchy though. if the variable 'a' can be some falsey value like 0, [], or "", you'll get the alternative 'b' even when x > y.

  28. 2 years ago
    Anonymous

    >"there should be only one way to do it"
    >has multiple ways to do it
    >they are all ugly
    abandoning perl was a mistake

Your email address will not be published. Required fields are marked *