Python's "itemgetter" is very useful

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

Indently

Indently

Күн бұрын

Hello everyone (not you Bob)! In today's video we will be learning about itemgetter in Python. It's a really cool function that I just learned about recently, I never really thought about exploring the operator module until this popped up.
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels

Пікірлер: 121
@KevinOMalleyisonlysmallreally
@KevinOMalleyisonlysmallreally Ай бұрын
'I'm going to quickly edit this off screen' Got a good laugh.
@chx75
@chx75 Ай бұрын
By the time I type itemgetter, I'd have already finished a lambda expression.
@Michallote
@Michallote Ай бұрын
Or just use the builtin slice() for ranges
@BlackneeedWasHere
@BlackneeedWasHere Ай бұрын
Yeah me too
@BlackneeedWasHere
@BlackneeedWasHere Ай бұрын
extractor = lambda items, indexes: [items[i] for i in indexes]
@chx75
@chx75 Ай бұрын
@@BlackneeedWasHere I'd use indices as the plural of index instead
@Master_of_Chess_Shorts
@Master_of_Chess_Shorts 2 ай бұрын
Thanks for this quick overview. Great for working with complex dictionaries. sorted_records = sorted(records key=itemgetter('name, 'occupation')) or powerful sclicing get_fields = itemgetter(0, 5, 7) selected_fields = [get_fields(record) for record in records]
@DrDeuteron
@DrDeuteron 2 ай бұрын
Why not islice? Wait, no. That’s itertools.
@rxsputin
@rxsputin 2 ай бұрын
Thanks for showing us this hidden gem, I definitely practice on it.
@JohnBoen
@JohnBoen 2 ай бұрын
Immediately useful. Thanks
@vedpanse6168
@vedpanse6168 2 ай бұрын
Could we just use lambda expressions? Saves an import line.
@danielcrompton7818
@danielcrompton7818 2 ай бұрын
Yes
@itsmaxim01
@itsmaxim01 2 ай бұрын
it will probably be slower since it’ll call native bindings at least 3 times (function call, [0] and [n-1]). built in functions *usually* only make 1 native call, making them faster in most cases.
@vedpanse6168
@vedpanse6168 2 ай бұрын
@@itsmaxim01 thanks
@robosergTV
@robosergTV Ай бұрын
@@itsmaxim01 no one cares about speed, unless you code a game in C++
@owenknight9798
@owenknight9798 Ай бұрын
Excellent tip!!
@skanderghamgui5039
@skanderghamgui5039 Ай бұрын
OMG I have been working on an application on using python and I was struggling to get my items this video is a life changer ❤ When I started watching I was about to ask if this works on dictionaries and then once I saw that dict I was overjoyed 🎉🎉😁
@keagankemp6275
@keagankemp6275 Ай бұрын
Love it, great video thanks
@samarthpai5359
@samarthpai5359 Ай бұрын
leant something new! keep posting such videos
@sriharimithranca9631
@sriharimithranca9631 2 ай бұрын
Just used it 3 days before for sorting a list of dictionary based on a particular key
@Zancb
@Zancb Ай бұрын
I had no idea about slice() either. Thanks
@norbertdapunt1444
@norbertdapunt1444 2 ай бұрын
Awesome..
@EarlHutchingson
@EarlHutchingson Ай бұрын
itemgetter also has a cousin "attrgetter" which grabs attributes instead of items
@CrazyFlyKite
@CrazyFlyKite 2 ай бұрын
Bob was here!
@bart5557
@bart5557 Ай бұрын
Hahah I was like, dafuq was that. Rewind and play at 0.25x
@AnatoliyRU
@AnatoliyRU Ай бұрын
also you can put slices into itemgetter
@owenknight9798
@owenknight9798 Ай бұрын
And Thank you!!
@phsopher
@phsopher Ай бұрын
Doesn't seem very useful. Takes literally 3 lines of code to implement, doesn't seem worth the overhead of remembering that it exists.
@ilonachan
@ilonachan Ай бұрын
def itemgetter(keys: list[Any]) -> Callable[[Any], list[Any]]: return lambda obj: [obj[k] for k in keys] turns out it's two lines including function signature and type hints. In fact writing this adhoc wherever it's used might be clearer. (I haven't tested this code btw, so if it's wrong lemme know. Also it seems there's a way to encode "an object that can be indexed by a specific type" so those type hints can DEFINITELY be improved)
@lukekurlandski7653
@lukekurlandski7653 Ай бұрын
It could definitely be useful for parsing complex dictionaries.
@pawelabrams
@pawelabrams Ай бұрын
if it's implemented in operator, it might be compiled into the engine, making this operation blazing fast; if you're doing this op very frequently on a large dataset, that may be one of the optimalisations in PHP I use array_column a lot
@phsopher
@phsopher Ай бұрын
@@pawelabrams It's not, it's implemented in Python
@mrxDots
@mrxDots Ай бұрын
As always all operator methods is useful for custom parsers, not clean production code
@ashokkumar3Dline
@ashokkumar3Dline Ай бұрын
In between of video "bob was here" in yellow text, what's that.. ?😅
@paxdriver
@paxdriver Ай бұрын
If you used item getter on a list of functions isn't that a catalyst for metaprogramming in Python? It seems to me that could choose functions that choose functions infinitely, I think.
@BlackxesWasTaken
@BlackxesWasTaken Ай бұрын
What font are you using? I can't seem to find it whatsoever. Looks like JetBrains Mono but for some reason mine looks a little... more edgy
@caesar104
@caesar104 2 ай бұрын
Hey, can you make a video about seeing what's inside a module's function, I mean actual source code of a module's method. E.g. comb function in math module. By the way, thx for great videos. I've learned a lot from you.
@codingpointers
@codingpointers 2 ай бұрын
You can type help() in your terminal Then type math And you will see the documentation
@DrDeuteron
@DrDeuteron 2 ай бұрын
Import inspect
@caesar104
@caesar104 2 ай бұрын
@@DrDeuteron yes I tried, but it didn’t work for math.comb function
@caesar104
@caesar104 2 ай бұрын
@@codingpointers Yes. However, I don’t wanna see documentation about modules or methods. I wanna see exact source code of comb method not its documentation and I couldn’t figure it out.
@DrDeuteron
@DrDeuteron 2 ай бұрын
@@caesar104 the other option is go to your python distribution and find the code and read it. Just don’t alter it. (My spyder will open numpy source code when I raise an exception inside it……i don’t like it.)
@noertri618
@noertri618 Ай бұрын
We can use it in complex json, finally
@karixening
@karixening Ай бұрын
Would be neat if python objects accepted tuples in their [] methods like numpy did
@BlackneeedWasHere
@BlackneeedWasHere Ай бұрын
I just quickly made this extractor = lambda items, indexes: [items[i] for i in indexes] Deletes the need to import so this is a one-liner
@aaronvegoda1907
@aaronvegoda1907 2 ай бұрын
This could be quite a nice way to validate a json response. Especially if combined with a TypedDict. getter=itemgetter(*MyTypedDict.__annotations__.keys()) try: getter(json_response) print(“All good”) except KeyError: print(“Invalid response”)
@LDericher
@LDericher Ай бұрын
I'd probably opt for pydantic whenever it's about input validation.
@mdtajhasan853
@mdtajhasan853 2 ай бұрын
Built-in data types and built-in functions are same??????
@philstubblefield
@philstubblefield 2 ай бұрын
I was surprised that you didn't also cover `operator.attrgetter()`. Next video?
@Indently
@Indently 2 ай бұрын
Potentially!
@echtertimo
@echtertimo 2 ай бұрын
Just use slice data type?
@Indently
@Indently 2 ай бұрын
Watch the whole video, and you will learn the difference between both.
@GabrielSantos_Jones
@GabrielSantos_Jones Ай бұрын
Bob was here?!
@Splish_Splash
@Splish_Splash 2 ай бұрын
I believe it was me who commented something about itemgetter below one of your polls.
@terabhaininja9
@terabhaininja9 Ай бұрын
Which IDE are you using?
@stickmandaninacan
@stickmandaninacan Ай бұрын
I think I recognize it as the IDE I use - PyCharm
@terabhaininja9
@terabhaininja9 Ай бұрын
@@stickmandaninacan ohhh okay thank you!!
@U53RN07F0UND
@U53RN07F0UND Ай бұрын
Oh, you just get an error if the key/index doesn't exist? So just define your own getter that let's you specify a default if the key/index doesn't exist. Got it.
@luziferius3687
@luziferius3687 Ай бұрын
there's defaultdict in the collections module
@bobwinslow1920
@bobwinslow1920 Ай бұрын
Doesn't lambda already do this? I will say that this looks a bit cleaner.
@blue_birb
@blue_birb Ай бұрын
practically just a lambda function though isn't it?
@lux-ray621
@lux-ray621 Ай бұрын
namedtuple is based on itemgetter
@dropalways
@dropalways 2 ай бұрын
fr
@misamee75
@misamee75 2 ай бұрын
Why the returned value is declared as "itemgetter" type instead of tuple or list?
@landsgevaer
@landsgevaer 2 ай бұрын
The itemgetter *itself* is an object. A function, if you like. Once you *apply* it to a list/dict, only then the resulting return value becomes another list/dict.
@DrDeuteron
@DrDeuteron 2 ай бұрын
*hint Nothing is,declared. But if = itemgetter does have the same information…idk.
@misamee75
@misamee75 2 ай бұрын
@@DrDeuteron What?
@DrDeuteron
@DrDeuteron 2 ай бұрын
@@misamee75 they’re type hints, not type declaration, X : str = math.sin Is working code.
@misamee75
@misamee75 2 ай бұрын
@@DrDeuteron, maybe before teaching me the difference between "declaration" and "type-hinting", you may want to work on your use of the English language so we can understand each other.
@khethanrg2889
@khethanrg2889 2 ай бұрын
Nice video. Can you explain `os.fork()` and `partial()` functions in python next?
@stevenbrown9185
@stevenbrown9185 2 ай бұрын
.....who's bob?
@davidmurphy563
@davidmurphy563 2 ай бұрын
We don't talk about Bob and his crimes.
@tigrankhachatryan6119
@tigrankhachatryan6119 2 ай бұрын
In my personal opinion, using a lambda would be better and less confusing. After all, this is the kind of thing lambdas are designed for.
@Master_of_Chess_Shorts
@Master_of_Chess_Shorts 2 ай бұрын
yes but itemgetter is written in C, much faster execution on large dictionaries...
@tigrankhachatryan6119
@tigrankhachatryan6119 2 ай бұрын
@@Master_of_Chess_Shorts From a more abstract and less practical point of view, that makes the feature only useful for overcoming the limitations of CPython.
@Master_of_Chess_Shorts
@Master_of_Chess_Shorts 2 ай бұрын
@@tigrankhachatryan6119 ok, hard to tell without specific use cases. I like these quick videos that just cover a simple operator. I also like all the comments it triggers from people like you. ;)
@Indently
@Indently 2 ай бұрын
A few people pointed out that they rather use lambdas, but ironically one of the most common places you will see this being used, is in fact, inside a lambda xD
@InforSpirit
@InforSpirit Ай бұрын
​@@Master_of_Chess_Shorts Operator is python file and everything inside of it will run as fast as anything else. Itemgetter is normal python-object. In this case lambda and other pure-functions most likely are faster, because you don't create object-memory and interface.
@aluc7
@aluc7 2 ай бұрын
whos bob?
@falklumo
@falklumo Ай бұрын
Using this certainly violates the KISS principle, makes code both longer and less understandable.
@sdvogo1520
@sdvogo1520 Ай бұрын
My that my nick is Bob ; - (
@nevokrien95
@nevokrien95 Ай бұрын
This is just overcomplicated and is less modifiable. Just wrote the dam functions. Unless this is faster
@Sinke_100
@Sinke_100 2 ай бұрын
f = lambda x: (x[0], x[-1])
@DrDeuteron
@DrDeuteron 2 ай бұрын
Assigning lambdas is considered gauche
@Sinke_100
@Sinke_100 2 ай бұрын
@@DrDeuteron it's the most amazing thing
@Indently
@Indently 2 ай бұрын
ahahaha
@Sinke_100
@Sinke_100 2 ай бұрын
itemgetter = lambda *args: lambda x: tuple(x[i] for i in args) it's basically this
@FakeMichau
@FakeMichau Ай бұрын
It would be fine if it compiled to the same code, but because it's python - it doesn't
@mastertech901
@mastertech901 2 ай бұрын
Another way to get the first and last elements of a list or tuple >>> elements = [1, 2, 3, 4, 5] >>> elements[0::len(elements)-1] [1, 5]
@patriotir
@patriotir 2 ай бұрын
Can you please make a video on how to land a job for self-taught programmers.
@EarlHutchingson
@EarlHutchingson Ай бұрын
don't call itemgetter a builtin function, that has special meaning in Python
@Indently
@Indently Ай бұрын
What do you recommend I call it?
@EarlHutchingson
@EarlHutchingson Ай бұрын
@@Indently a standard library function
@DrDeuteron
@DrDeuteron 2 ай бұрын
If just used this code, though I called it heels 👠….like it operatorates on types.LoafType.
@maleldil1
@maleldil1 2 ай бұрын
While I appreciate the usage of type hints to remind people that they are important and should be used, typing local variables like this is just poor form.
@K0D0R0
@K0D0R0 2 ай бұрын
I disagree.
@Cloud-kd7mx
@Cloud-kd7mx Ай бұрын
it helps with weird cases like the itemgetter, when you don't exactly know what it is. But yeah, in other scenarios, i prefer to use it only for function parameters and return types
@davidmurphy563
@davidmurphy563 2 ай бұрын
Are you really ok with a third of your code being pointless type hinting boilerplate?? Why don't you at least try dropping it for a while? At least until the first time you get your types mixed up when coding for real. You know, forever, because nobody coding dynamically with more than ten minutes experience ever, ever makes that mistake. The whole "type safety" thing is myth. That game across as grumpy... Sorry! It's early!
@maleldil1
@maleldil1 2 ай бұрын
What's bad here is not type hinting but the fact that it's completely unnecessary in this case. You don't need to type local variables because the type checker is able to perform local type inference, and you can verify this by hovering over the variable. Type hinting is mostly useful for function signatures, dataclasses, etc., where it becomes an important tool for defining interfaces. Since you would probably have to describe the types your function accepts and returns in the docstring anyway, you might as well define them in a way that can be checked by automated tools. > nobody coding dynamically with more than ten minutes experience ever, ever makes that mistake That is just false. The huge number of "undefined is not a function" you see in the wild from Javascript is enough to disprove that claim. There's a reason static typing came back in full force in recent years, as mainstream languages become better at type inference and reduce the burden of typing (which again, is not what happens in this video).
@tiongah7690
@tiongah7690 2 ай бұрын
exactly, the more time I watch your video, the more I find it annoying
@davidmurphy563
@davidmurphy563 2 ай бұрын
@@maleldil1 Sure, there are fringe use cases; it's necessary with dataclasses and if you want to recompile into C for example. And yeah, there a few minor conveniences with IDEs which claw back a tiny fraction of your wasted time. I'm not sure what js has to do with the price of fish. Ghastly language. Honestly, it's enough to discuss this in python, next thing we'll be bringing up fortran and algol - or, god forbid, haskell - and all hope for humanity will be lost.
@chx75
@chx75 Ай бұрын
Some one told him to "type your code in the video". As he was not sure what they meant, he did both.
@claer000
@claer000 2 ай бұрын
Bob was here !
Python's 5 Worst Features
19:44
Indently
Рет қаралды 90 М.
3 Bad Python Habits To Avoid
10:40
Indently
Рет қаралды 47 М.
ROCK PAPER SCISSOR! (55 MLN SUBS!) feat @PANDAGIRLOFFICIAL #shorts
00:31
2000000❤️⚽️#shorts #thankyou
00:20
あしざるFC
Рет қаралды 16 МЛН
Watermelon Cat?! 🙀 #cat #cute #kitten
00:56
Stocat
Рет қаралды 33 МЛН
5 Really Cool Python Functions
19:58
Indently
Рет қаралды 45 М.
15 Python Libraries You Should Know About
14:54
ArjanCodes
Рет қаралды 364 М.
Python: A Quick Guide To Type Annotations (ft. Mypy)
11:25
Indently
Рет қаралды 27 М.
How To Use Recursion In Python
8:50
Taylor's Software Solutions
Рет қаралды 3,7 М.
What is "@total_ordering" in Python?
11:12
Indently
Рет қаралды 20 М.
why do header files even exist?
10:53
Low Level Learning
Рет қаралды 363 М.
TypeScript Generics are EASY once you know this
22:21
ByteGrad
Рет қаралды 124 М.
5 Cool Python One-Liners
12:23
Indently
Рет қаралды 26 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 374 М.
"Stop Using Async Await in .NET to Save Threads" | Code Cop #018
14:05
ROCK PAPER SCISSOR! (55 MLN SUBS!) feat @PANDAGIRLOFFICIAL #shorts
00:31