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
Nothing Ever Happens Shirt $21.68 |
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
Nothing Ever Happens Shirt $21.68 |
Nice trick anon but isn't that also possible with ternary operators?
Its because Python evaluates "False" as 0 when accessing a tuple
I guess it a neat trick for code golfing.
Yup, nvm
z = (a, b, c)[True + 1]
based, checked and True + 1, returns the 3d element.
Speaking of code golfing here's how you import inline.
list(__import__('itertools').product(range(10), repeat=2))
That's kind of wild anon.
Does Python have ternary operator?
yeah but it's written more unusually than most languages
result = x if a > b else y
z = b if x > y else a
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
z = (a, b)[(not x < y) if x > y else 1]
>It assigns z to a
it assigns a to z
z = (a, b, c)[(not x < y if x > y else 1) if not x == y else 2]
for a, b in zip(x, x[:1]):
... #this is also a trick, ellipsis is a valid placeholder nowadays
sorry should be x[1:]
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)]
>le python is le simple language
>only one way to do things
Explain yourselves pythoBlack folk.
>le putting words into people's mouths
>Hasn’t heard of the zen of python
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.
I wonder how long before I can be a pro-python ML coder
readable code > "le tricks"
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.
>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.
>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
>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
He is clearly summing all 3 Trues. Seems like the appropriate response.
If it has to do something then it might as well do that, but a TypeError might be better.
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])
Beautiful
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)}
Shit meant to tag OP
You can do the same thing without the map by using the dict constructor
d = dict(I.split(“=“) for I in some_list)
>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
It's not really that hard, moron. You should learn an easier language, I suggest Scratch.
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.
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).
os.execvp('guile', ['guile'])
My only trick is using sets, sets are fast, fast sets make python fast, fast fast gotta go fast.
you mean tuples right?
Sets can't you read motherfricker, sets!
oh you're moronic
sets are not tuples
idk what you're whining about
where would you replace a data structure with sets where it is not already a set?
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
Sets are the slowest container type to construct, but are fast for doing membership test and disjoint tests
>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
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.
With the addition of generics, I'll bet that a set DS might be added to the stdlib.
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")
based and rust pilled.
my trick is to just use starlark instead.
ok, troony
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.
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
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.
# naive swap
a = 10
b = 3
temp = a
a = b
b = temp
# pythonic swap
a = 10
b = 3
a, b = b, a
>pythonic
This fricking buzzword makes me feel the same as Hispanic when they hear the word "latinx"
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
i mean you can say "more idiomatic python code" or "pythonic", kinda rolls off the tongue
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"
Why?
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
>What python tricks do you like the most?
import pandas as pd
learn how this ONE SIMPLE TRICK can get you a job IN LESS THAN TEN MINUTES
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.
hello fellow pythonistas
is it possible to achieve dot notation with python dictionaries?
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.
_ is placeholder for whatever is has been previously returned
>>> f = lambda x: x**2
>>> f(2)
4
>>> _**2
16
This is only true in the repl.
These become particularly interesting if you use comprehensions.
nums = [3, 8, 7, 4]
if all(n >= 5 for n in nums):
...
I also like filter and reduce, even though I've never used them in python code
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)
install J: https://code.jsoftware.com/wiki/System/Installation
what do square brackets do
indexing operator
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.
>"there should be only one way to do it"
>has multiple ways to do it
>they are all ugly
abandoning perl was a mistake