10 Crazy Python Operators That I Rarely Use

  Рет қаралды 43,409

Indently

Indently

Күн бұрын

Пікірлер: 117
@__christopher__
@__christopher__ Ай бұрын
There's also the successor operator -~ with -~0 = 1, -~1 = 2, ...
@Indently
@Indently Ай бұрын
That's incredible, thanks for sharing this!
@okkoheinio5139
@okkoheinio5139 Ай бұрын
This is so cursed. for those who don't get it, taking the negative of a two's complement (the common way to represent signed integers) integer is equivalent to "bitwise not, then increment" (try thinking about what -~i means, then, before I spoil it) what this is doing is taking the negative (-) of the bitwise not (~), resulting in "not, not, increment", the nots cancelling each other out. excercise for the reader: how would you construct "decrement" using this knowledge?
@MrRyanroberson1
@MrRyanroberson1 Ай бұрын
and the predecessor operator ~-
@JunxiSalamander
@JunxiSalamander Ай бұрын
The wrong script run, as always (relatable)
@GhostShadow.0316
@GhostShadow.0316 Ай бұрын
Python Developer:
@NostraDavid2
@NostraDavid2 Ай бұрын
*_, is not a single operator but a modifier, a variable and an operator (in that order). The comma will unwrap the object right of the equals, the underscore will act like a variable, and I'm actually not sure of the asterisk. I guess it does the list conversion?
@AndrewI-n5l
@AndrewI-n5l Ай бұрын
The asterisk returns (x for x in "Python")
@pidgeonpidgeon
@pidgeonpidgeon Ай бұрын
Python can assign a pattern on the right to a tuple on the left. The underscore is just the variable name, the asterisk takes anything no already captured and the comma makes it a one element tuple
@xaf15001
@xaf15001 Ай бұрын
I don't think the comma does anything, since it was in the context of where it's used to separate variables. The asterisk is the one that unwraps the list.
@Fasalytch
@Fasalytch Ай бұрын
​@@xaf15001comma is the "create a tuple" operator
@jursamaj
@jursamaj Ай бұрын
@@xaf15001 It's complicated. If you do 'x,*ˍ = ' it will put the 1st element of the iterable in x and all other elements in a list in 'ˍ'. Conversely, if you do '*ˍ, x = ', it will put the last element in x and all others in a list in 'ˍ'. But you can't do '*ˍ = '. That will produce an error that the left hand side must be a list or tuple. But '*ˍ, = ' makes it a tuple of 1 element, and puts all the elements of the iterable in a list in 'ˍ'. (Note: the right hand side can be any iterable: string, list, tuple, set, dict, generators, etc. Edited because YT uses asterisks and underscores as markup.
@tha_karatejoe
@tha_karatejoe Ай бұрын
My personal projects grow more esoteric and illegible by the day
@joelneely
@joelneely Ай бұрын
I really appreciate your coverage of the full range of Python functionality. It is very helpful. I would like to suggest that some of the “value judgment“ terminology may be less helpful. For example, to someone who is very comfortable with the syntax pattern, the appearance of //= is not “weird”. It is still fair (IMHO) to offer the caveat that it is less commonly used, and therefore may slow down readers of the code who need to stop and figure it out.
@DuncanBooth
@DuncanBooth Ай бұрын
`*_,` is useful when combined with other variables in the unpacking. e.g. >>> first, *_, last = "Python" >>> first, last ('P', 'n')
@hufuhufu
@hufuhufu Ай бұрын
That is sick. I assume you can do more than just first and last? Something like >>> first, second, *_, beforeLast, last = "Python" should be possible I reckon?
@mahdoosh1907
@mahdoosh1907 Ай бұрын
the ^ operator works like xor for integers, which i use so many times for data science
@NostraDavid2
@NostraDavid2 Ай бұрын
~ is indeed pronounced "tilde" 😊
@chixenlegjo
@chixenlegjo Ай бұрын
Well it’s spelled that way, but pronounced “till duh”
@vnc.t
@vnc.t Ай бұрын
​@@chixenlegjono, it's tilda, not tildeh or tilde
@8jn9
@8jn9 Ай бұрын
/ˈtɪldə,ˈtɪldi/
@andreyv116
@andreyv116 Ай бұрын
4:55 unary bitwise complement; its dunder is __invert__
@gigsoll
@gigsoll Ай бұрын
This operations on sets was in my university tests at cybernetics. I never used them to write my scripts but should to learn by hard for exam
@tochimclaren
@tochimclaren Ай бұрын
Learn this for job security 🏃‍♂️
@jperez7893
@jperez7893 Ай бұрын
some of these can be used for non-maintainable code
@AndrewI-n5l
@AndrewI-n5l Ай бұрын
Not everything has to be demure darling, and you should be able to look at a @ b and know what it does
@eliavrad2845
@eliavrad2845 Ай бұрын
All of these can be used for non-maintainable code. The cool ones can't be used for maintainable code
@e_psi_lon
@e_psi_lon Ай бұрын
The floor division result is the quotient of the euclidian division. That's how I learned it
@knghtbrd
@knghtbrd Ай бұрын
I remember a time when Python did not have //, even before we got it from __future__. Python did different things based on the type of numbers back then, which again made sense if you used other lower-level languages but what a pain in the arse to explain to someone new. The // floor-division operator provides the effect of integer division (discard the remainder, return an int) in a way that was more consistent and leave the normal / to do "normal" division. Again, this stuff tends to make sense when you're doing bitwise operations, and while I do those in Python, I'm not surprised if others don't. That last one… 😬 It WORKS, but if you use it as anything other than this video, yikes.
@umlucasalmeida
@umlucasalmeida Ай бұрын
For data wrangling I use ~ all the time!
@RazeVX
@RazeVX Ай бұрын
wouldnt call the operators crazy and i knew most of them but some py shinanigans like the last one where new to me so i would call the video informative. well done keep it up.
@smorales9492
@smorales9492 Ай бұрын
I like to call the "//" the ✨smooth operator ✨
@urknidoj422
@urknidoj422 Ай бұрын
This is interesting! It means you can use: --------------------------------------------------------0 ~~~~~~~~~~~~~~~~~~~~~~~0 ++++++++++++++++++++++++++++0 as separators without causing any errors
@richardboreiko
@richardboreiko Ай бұрын
Tilde is correct regardless of whether you pronounce the e. And I always follow the rule that correct is in the ear of the listener.
@patrickbg110
@patrickbg110 Ай бұрын
Love the last one!
@RocketLR
@RocketLR Ай бұрын
"AM I ILITERATE?!" Somedays i ask myself the same question...
@zealotoffire3833
@zealotoffire3833 Ай бұрын
4:53 you got it correct, it is called a tilda good job (i don’t know how to spell it i think thats right)
@danik0011
@danik0011 Ай бұрын
tilde
@drew.esbssy
@drew.esbssy Ай бұрын
Pistol operator is now my favourite
@NostraDavid2
@NostraDavid2 Ай бұрын
Man, that @ (at) operator took me by surprise! 😆
@mudi2000a
@mudi2000a Ай бұрын
The @ operator is not a standard Python operator but is introduced only by NumPy. Therefore also in my opinion it doesn't count.
@knghtbrd
@knghtbrd Ай бұрын
We've come a long way since… from operator import mul print(sum(map(mul, A, B))) 😁 (There isn't a convenient operator for dot products that I know of.) Dot and cross products are used a lit in 3D stuff, which is the major reason I learned any of that.
@michealkinney6205
@michealkinney6205 Ай бұрын
"But the benefit of using this approach is that it gives you this funny face back... that kind of looks like eh" @ 4:42. Lol
@stalker32041
@stalker32041 Ай бұрын
7:56 when writing a cmd simulator. `cmd, *args = "call a b c".split(' ')`
@SHAMIKII
@SHAMIKII Ай бұрын
Thank you very much for your videos
@matthewhsu7299
@matthewhsu7299 Ай бұрын
Thank you so much!
@anon_y_mousse
@anon_y_mousse Ай бұрын
Personally, I like weird esoteric constructions. Have you heard of the IOCCC? Maybe there should be an IOPCC.
@PanduPoluan
@PanduPoluan Ай бұрын
You really should introduce people to the awesome f-string which makes operations clear ... Like instead of print(a-b), do this instead: print(f"{a - b = }") And so on.
@danik0011
@danik0011 Ай бұрын
slight syntax error: f"a - b = {a-b}" (the part in {} is evaluated)
@xMurdererr
@xMurdererr Ай бұрын
@@danik0011 it’s not a syntax error. f”{a - b = }” is equivalent to f”a - b = {a - b}”
@dipeshsamrawat7957
@dipeshsamrawat7957 Ай бұрын
Thank you 😊
@eJuniorA2
@eJuniorA2 Ай бұрын
the last one made me lose my job, ty
@Juju_en3d
@Juju_en3d Ай бұрын
Waaaah such operators, it looks like my cat coding with my computer
@houstonbova3136
@houstonbova3136 Ай бұрын
Do you use the walrus operator? Super useful in if statements so you don’t have assign a value twice.
@PeterZaitcev
@PeterZaitcev Ай бұрын
The last one looks like a Morse code
@molvenma1446
@molvenma1446 Ай бұрын
~ operator have cool combination with - ~-a is equal to a-1 and -~a is a+1 They are operator sperm right and left. (because of the tail)
@DrDeuteron
@DrDeuteron Ай бұрын
Wait, what? How long has there been a matmul dunder bound to 🐌?
@Indently
@Indently Ай бұрын
As far as I know, as long as you import numpy, it's been there for quite a while!
@vytah
@vytah Ай бұрын
It's available since Python 3.5. Initially, literally nothing used it, as it's completely unused in the standard library.
@valorien1
@valorien1 Ай бұрын
The difference between `var = list(iterable)` and `*var, = iterable` is that the `*var` approach is around 10ns faster (Python 3.12). Definitely not worth it. Stay with `list(var)`.
@MrMoon-hy6pn
@MrMoon-hy6pn Ай бұрын
Really? In python 3.12 using timeit I consistently got about ~180ns for “*x,” and ~140 for list(x) or about 40 ns faster for the list approach. Doesn’t really change the takeaway but still.
@valorien1
@valorien1 Ай бұрын
@@MrMoon-hy6pn Yeah, not sure why we're seeing different results on 3.12. I've now re-tested using Python 3.13, and `list(x)` is indeed around 40ns faster than `*x`. I guess that settles it🙂
@warmCabin
@warmCabin Ай бұрын
~ is the squiggle, everyone knows that
@steff1238
@steff1238 Ай бұрын
interesting that -11//3 = -4 and int(-11/3)=-3 ..
@OnDragi
@OnDragi Ай бұрын
int(number) returns the number truncated to a whole number. A float number is represented the same way when it is positive or negative, just with a sign bit being different-so we get truncation towards zero: int(-1.1)=-1, int(-0.1)=0, int(0.1)=0, int(1.1)=1. The // is best understood together with % (modulo operator): for two numbers, a and b, we always want a = (a // b) * b + (a % b) to hold and we always want (a % b) to be a non-negative number smaller than b. Therefore, if a = -11 and b = 3, we have no choice but to write it as a = -4*3 + 1.
@knghtbrd
@knghtbrd Ай бұрын
The clue is in the name: "Floor-division": >>> from math import floor >>> floor(-11/3) -4 floor() returns the largest integral (integer) value
@KosstAmojan
@KosstAmojan Ай бұрын
Since you asked here's a list of (American English) names for some of the weird characters that came up: ~ tilde (til duh) (you got this one right) & ampersand @ commat (comm at) ^ carat (pronounced "carrot") Side note: concerning the "pistol operator", I like to call it the "spread operator", which I got from JavaScript but I'm pretty sure is used in several other languages. It takes the individual elements of an iterable and "spreads them out."
@TheJamesM
@TheJamesM Ай бұрын
I wouldn't say "commat" is the most common name for @; I'd say that's jargon only familiar in certain fields. It's short for "commercial at", which is probably a little more standard, but in my experience by far the most common name is simply "at sign".
@proton..
@proton.. Ай бұрын
4:55 yeah, thats a tilde
@agatemosu
@agatemosu Ай бұрын
and a virgulilla
@maksimluzin1121
@maksimluzin1121 Ай бұрын
Well, how the matrix mult @ will work together with the same @ decorator symbol in the same program? Will that generate an error?
@AndrewI-n5l
@AndrewI-n5l Ай бұрын
Absolutely not. Python interprets things in context. You use ( ) for both function definitions and tuples, and it's not an issue. Likewise, the set operators also do bitwise operations, IN CONTEXT. 😁
@indigojones4442
@indigojones4442 Ай бұрын
Python's parser understands the difference between @ when used as a binary infix operator, and @ when it is a prefix of a name in the global scope decorating a function definiton. The @ symbol is in fact a binary operator at all times in python, there's just no default behaviour for it. You can create behaviour for it by implementing the __matmul__ method in your classes.
@maksimluzin1121
@maksimluzin1121 Ай бұрын
Thanks!
@jamesgray6804
@jamesgray6804 Ай бұрын
I've been using python for ages and I'd never seen this before!
@drdca8263
@drdca8263 Ай бұрын
@@indigojones4442doesn’t have to be in global scope though?
@oliverli9630
@oliverli9630 Ай бұрын
11:09 No! This is Morse code haha
@endersteph
@endersteph Ай бұрын
I use //= quite often actually!
@antoinebugnicourt808
@antoinebugnicourt808 Ай бұрын
Used it just yesterday to code a custom base conversion function from integers to strings, very useful to loop through the steps of a euclidean division!
@gvarph7212
@gvarph7212 Ай бұрын
Worst operator thing I've ever seen was in C, and it looked something like `a++ + ++b`
@realitant
@realitant Ай бұрын
I take it you don’t do much bit manipulation
@umairyounuus108
@umairyounuus108 Ай бұрын
What is the reference to these operators??
@KnightOfChess
@KnightOfChess Ай бұрын
That was fun😂😂
@q.u.e.r.t.y
@q.u.e.r.t.y Ай бұрын
5:24 But doesn't flipping it like that result to 10 instead of -6?
@enzozbestetti5992
@enzozbestetti5992 Ай бұрын
I suspect Python is interpreting numbers as Two's complement binary, that's why you get negative numbers.
@alexander6011
@alexander6011 Ай бұрын
as it's a signed integer, no. google "twos complement".
@TheJamesM
@TheJamesM Ай бұрын
Yes, he ignored the leading zeros which really confuses the explanation. For those unfamiliar: Internally the int is represented by a fixed number of bits, regardless of how big it is (or, more accurately, it will automatically choose from a set of predetermined int sizes depending on the value). When you do bitwise negation, that affects all bits, including the leading zeros. Since Python (like most programming languages) uses two's complement, the most significant bit represents whether the number is positive (0) or negative (1). The reason why flipping 5 becomes -6 (rather than -5) is because it simplifies the internal workings of integer addition, and removes what would otherwise be a resundant double representation of zero - this is called one's complement, and it's less useful. One's complement works like this: positive integers work like standard mathematical binary, and are denoted by the most significant bit being 0. Negative integers are simply their bitwise negation (i.e. every bit is flipped to its opposite value. So, for 8-bit integers: 00000101 = 5 11111010 = -5 This divides the space perfectly equally between positive and negative integers, but it leaves two different representations of zero: 00000000 = 0 11111111 = -0 There can be contexts where negative zero is a useful concept, but that's a little esoteric for most uses. Also, a naïve implementation of addition would have -0 + 1 = 0: 11111111 + 00000001 = 00000000 (overflow) Two's complement works almost the same way, except the value of each negative integer is one less than what it would be in one's complement: 11111111 = -1 11111010 = -6 This way there is only one representation of 0, and the addition logic can be very simple. The only slightly odd effect is that, because zero takes up a spot in the positive half, the lowest representable negative value is greater in magnitude (by one) than the highest representable positive value. That doesn't really matter, but it _feels_ a bit peculiar!
@Jason-b9t
@Jason-b9t Ай бұрын
​@@TheJamesMBasically correct, but there is a problem. The integer does not have -0. The reason why 0b1...1010 is -6 is that when added to 6 (0b0...0110), it will be 0. 0b11...1010 (x) +0b00...0110 (+6) =0b00...0000 (=0)
@TheJamesM
@TheJamesM Ай бұрын
@@Jason-b9t Sorry, I wasn't being very clear. I was specifically saying that that's what it _doesn't_ do (i.e. two's complement doesn't have -0). 0b000... and 0b111... at the end of my message are saying how it works in one's complement. I'll edit to clarify.
@xXherbal1stXx
@xXherbal1stXx Ай бұрын
wrong script error is starting to become a running gag 😅
@visantibanez
@visantibanez Ай бұрын
Funny one
@joyinfant3241
@joyinfant3241 Ай бұрын
Assume
@NostraDavid2
@NostraDavid2 Ай бұрын
Saying "pipe" instead of "or" is, IMO, doing a disservice to newbies to Python. | = or - = without / subtract ^ = not & = and The symbols are the same as the bit-wise operands, but they act like their logical variants which are words in Python (or, and, not - the minus is a weird outlier).
@NostraDavid2
@NostraDavid2 Ай бұрын
Same for |= being an or operator for the keys in the dict.
@largewallofbeans9812
@largewallofbeans9812 Ай бұрын
I’d say XOR rather than “not” for ^
@pidgeonpidgeon
@pidgeonpidgeon Ай бұрын
~ is not ^ is xor
@jackzugna5830
@jackzugna5830 Ай бұрын
One important thing to know is that normally these operators (~ | & ^) work on the individual bits of a variable; the reason they also work on other objects in Python is due to "operator overloading," meaning the same symbol and operation are maintained but applied to different objects. To better understand this, one should study a bit of C++. If transitioning from Python to other languages, it's important to remember that ~ is different from !, even though both are "not," but ! performs an implicit conversion to bool; the same applies to & and &&. I think it's better to learn certain things from other languages rather than Python.
@suwapete9761
@suwapete9761 Ай бұрын
^ = XOR because it gives the set where elements are (in A) XOR (in B)
@MRA2_2
@MRA2_2 Ай бұрын
I learnt language paytho and made some project hop all see and give me werit
@Keithfert490
@Keithfert490 Ай бұрын
The "correct" way to use the "pistol operator" is to not use it and to write x = list(y) instead of *x, = y
@CarlosGonzalez-mp9re
@CarlosGonzalez-mp9re Ай бұрын
7:53
@lux_film3314
@lux_film3314 Ай бұрын
Maybe one-day you'll teach us how-to use regular expressions in python?
@drdca8263
@drdca8263 Ай бұрын
r’your regex here’ (r for raw. Reason for using this is so that you don’t need to escape your backslashes in order to use them as escape codes in regex) and the regex library re.match etc. I don’t know why I watched this video… I guess it was useful to learn that the dunder method for @ is matmul, but like, I could have quickly looked that up if I wanted to use it. I guess I was procrastinating by watching the video. If you want to know how to use regex in Python, you are best off reading the docs imo, not waiting for a channel to release a tutorial on it.
@johanildpg5414
@johanildpg5414 Ай бұрын
First!
@xeridea
@xeridea Ай бұрын
floor division operator is odd since // in many languages signifies a comment.
@enzozbestetti5992
@enzozbestetti5992 Ай бұрын
The // operator does not always round down, that's a confusing way of putting it. Rather it truncates towards zero for positives and away from zero for negatives. For example, say the result of a division with a single / is -4.66657585. If instead we used //, the result would be -5, not -4.
@NishithSavla
@NishithSavla Ай бұрын
That's what rounding downwards means right?!
@enzozbestetti5992
@enzozbestetti5992 Ай бұрын
@@NishithSavla in pure mathematics terms yes. But a lot of people forget that negative numbers are in "reverse" so they tend to just discard the decimal and keep the number which is not correct
@victorsago
@victorsago Ай бұрын
That's literally how "floor division" works.
@NishithSavla
@NishithSavla Ай бұрын
​@@enzozbestetti5992 that's called a skill issue man.
@callbettersaul
@callbettersaul Ай бұрын
That's literally what it does. It always rounds down. If a person doesn't understand, that -5 is smaller number than -4, then that's their problem.
StrEnum & IntEnum: New Enum Types In Python?
8:07
Indently
Рет қаралды 14 М.
5 Wacky Python Features
15:37
Indently
Рет қаралды 16 М.
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 88 МЛН
А я думаю что за звук такой знакомый? 😂😂😂
00:15
Денис Кукояка
Рет қаралды 3,1 МЛН
5 Awful Python Mistakes To Avoid
22:13
Indently
Рет қаралды 27 М.
Some silly number systems
8:17
Random Andgit
Рет қаралды 200 М.
Learn Python OOP in under 20 Minutes
18:32
Indently
Рет қаралды 107 М.
Python Modules, Packages, and Virtual Environments (Beginner Friendly)
11:32
10 Neat Ways To Use Underscore In Python
18:17
Indently
Рет қаралды 23 М.
5 Really Cool Python Functions
19:58
Indently
Рет қаралды 66 М.
5 Python Libraries You Should Know in 2025!
22:30
Keith Galli
Рет қаралды 20 М.
10 Important Python Concepts In 20 Minutes
18:49
Indently
Рет қаралды 300 М.
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 88 МЛН