HomeНаука и техникаRelated VideosMore From: Sebastiaan Mathôt

7 Simple Tricks to Write Better Python Code

4303 ratings | 222963 views
Visit http://python.cogsci.nl/ for more tutorials! Seven solutions to common small problems that Python programmers often solve in a suboptimal way. This video is understandable for beginners, but also contains useful advice for experienced programmers. - 0:50 Using enumerate() - 3:22 Using zip() - 6:35 Tuple unpacking - 9:40 Default dict values - 12:42 For ... else - 16:13 File reading with 'with' - 19:40 Exception handling
Html code for embedding videos on your blog
Text Comments (342)
yuvlal83 (11 days ago)
Finally got the finally
Susan Amber Bruce (23 days ago)
Take a look at me, everything I own's iced out Pimp baby, you can see my wrists with the lights out. This is how I do it, mad bitches and clothes Godfather baby, only play to my rogues. What does all this mean anyone?
Excellent one. What editor are you using to run your python code?
Thanks +Sebastiaan Mathôt
Sebastiaan Mathôt (21 days ago)
It's OpenSesame (https://osdoc.cogsci.nl/), an IDE that's specific for creating psychology/ neuroscience experiments. But it's also very useful for these kinds of demos!
Jon Burke (27 days ago)
Curious which IDE he uses. Anyone any idea?
Jon Burke (27 days ago)
Nvm, just found it myself down the comments. For anyone curious, it's called 'OpenSesame'
pgo eds (1 month ago)
7:45 also done in Perl if you use ()
Спасибо, весьма полезное видео :)
Dhananjay Kansal (1 month ago)
Lovely! Absolutely lovely! Regards to you sir.
usharam balik (1 month ago)
Trick #5: Why not use ‘if needle in haystack’ ?
Tyler Poelking (2 months ago)
Good video my man. Would have loved to see a link to all the code in the the description
Sebastiaan Mathôt (2 months ago)
I'm afraid that for this video I didn't make the code available. For all my more recent videos, I have though!
Tyler Poelking (2 months ago)
This man has a sense of humor
Tushar Niras (2 months ago)
well, this video was really good for me ... I'm a beginner and want to know write code right way ... It was helpful ... thanks! waiting for more
齋藤謙介 (2 months ago)
'dick' is UGLY LOL NO JOKE!d:D
hunar omer (2 months ago)
nosalan (2 months ago)
Amandeep kaur (2 months ago)
https://www.youtube.com/watch?v=pacgPCgaY9A learn python in 2 minutes
ka totoy (3 months ago)
What software (IDE) is he using?
Rich Plewa (3 months ago)
I looked at your website and one of the 1st thing I see is Input and Output. The docs on Python make it difficult to find and use the input statement. You put it right on the top Thanks.
Johnny From The Space (3 months ago)
Thanks a lot :)
mike lee (4 months ago)
Great video! super helpful!
Илья Иванов (4 months ago)
Omg! It is perfect! Early i was using: x = m_dict['Dick'] if 'Dick' in m_dict else None It was total wrong((( Thank you vm!
Minas Kamaratos (5 months ago)
there is a whole book filled just with tips like this, Effective Python by Brett Slatkin. Improved the shit out of my python. I now also bash my keyboard next to the mic.
Elf Machine (5 months ago)
I realized you were Dutch after seeing Amsterdam in your list.
Sushant Kulkarni (5 months ago)
The good way for finding an element in a list could have been haystack.__contains__(needle), don't you think?
Sushant Kulkarni (5 months ago)
10:00 one can never be a 100% sure whether...
Zeling Kuang (6 months ago)
Great video! Thanks a lot! And I'm wondering which IDE do you use in this video?
Zeling Kuang (6 months ago)
Sebastiaan Mathôt  Ok, Thank you!
Sebastiaan Mathôt (6 months ago)
That's OpenSesame, a specialized IDE for developing psychology and neuroscience experiments. But also very useful for these kinds of demos!
ijw z (6 months ago)
at 14.49 why not do 'if letter in haystack: print('found') else: print('Not found!')
Siya Busakwe (6 months ago)
Put Dick in the dictionary
ddstar (6 months ago)
20 minutes too long
Stanly (6 months ago)
To check if a value is in an array, you can also use: if (needle in haystack) print("Found!") else: print("Not Found")
umamaheswar pgdds (6 months ago)
Vady (7 months ago)
Hmmm, at 15:00, the needle and haystack example, what if I don't want to use breaks? Like in the code I wrote for a bot, there could've been more than 1 needle, and if I were to break it after I find one, the other needles won't get found.
mau lopez (7 months ago)
Excellent tips, great audio and pace, thanks so much!
Aleksandr Saint (8 months ago)
Video is great, but m8: tip #5 - usage of "if needle in haystack: ..." would be better, no? I get it that the point was to show the else close after for loop :)
dasari gowtham (8 months ago)
Thanks 😊
J MacKay (9 months ago)
great info and ty for the tips, just some feedback - audio very difficult to deal with ;_; would strongly prefer a transcription of this lol
Surfer (9 months ago)
dude why Dick ?
I know, You talking about syntax constructions, but you should keep in mind, that some newbie python developer could use you'r examples as it presented in you'r video, just in copy-paste mode. In that scenario I would like to admit, that you should add an explanation about how dangerous it is to use just try: ... except: ... without any specified exception in "except" block. This is very ugly anti-pattern, you should warn about it!
doogieAfro (9 months ago)
There is a typo: if ('Dick' in ages) . You mispelt "Agnes". You're welcome.
The Academy (9 months ago)
Thank you for a good video!
Gallum (9 months ago)
"The pythonic way" thanks, stack overflow... no but forreal very helpful video that phrase is just overused and obnoxious.
M M (9 months ago)
Love the O.G. reference haha. Grandfather of gangster rap 💯
Clint Sullivan (10 months ago)
Sebastiaan Mathôt (10 months ago)
Awesome, thank you!
Almatik Dayanchik (10 months ago)
What kind of text editor do u use ?
Green Eggs and Ham (10 months ago)
ummm... 3 lines works for tip 1 without enumerate? cities = ['London', 'Paris','moscow','Berlin'] for city in cities: print(' the city :',city)
Green Eggs and Ham (10 months ago)
umm or for i in range(0, len(cities)): print(' the city :', i ,cities[i])
Green Eggs and Ham (10 months ago)
...ahh he wanted a counter printed too
Marwan Ghubein (10 months ago)
Very useful and informative
R (10 months ago)
I love your keyboard noises. Adds that kind of warmth to it
JK FRT (10 months ago)
Thanks, great video, good tips. Made me rethink a bunch of things from my current project.
cheuch (11 months ago)
Well done mate ! Everything in your video is neat, big font, clean explanations, examples already prepared. Big thumbs up and suscription from me. Cheers From France
Hurtful Axis (11 months ago)
KeyError dick :DD
Chao Zen (11 months ago)
if needle in haystack: print("found") else: print("Not found")
Instead of using %s or %d etc. in strings its so much easier to use {0}, {1}, etc. with the .format method because you don't need to worry about data types but get the same result.
lukas (11 months ago)
Die Hollanders toch he
hrishi chandanpurkar (11 months ago)
What IDE is that??
Sebastiaan Mathôt (11 months ago)
+hrishi chandanpurkar it's OpenSesame (https://osdoc.cogsci.nl/), an IDE for developing psychology/ neuroscience experiments.
Mengfei Li (11 months ago)
Great lecture, thank you.
guh (1 year ago)
Ere bos (1 year ago)
trick number 5, use: if needle in haystack: print("found") else: print("not found") OR you can do: print("Found" if needle in haystack else "Not found")
Vady (7 months ago)
that last line is possible? :O
zeppelin0110 (1 year ago)
Learned a few new things, for sure
Prog Nauts (1 year ago)
Thanks, your tutorials are so well explained..
Keijo228 (1 year ago)
11:25 I can't get how did you put lines in comments?
Sebastiaan Mathôt (1 year ago)
In OpenSesame (which is the IDE that I'm using), you can comment out blocks of code with Ctrl+M. Most (advanced) editors allow you to do this in one way or another.
Todd Carney (1 year ago)
This was a very helpful video. I think instead of saying one way is "bad" and the other is "good," though, I think it would be more accurate to say "good" and "better." Each of the "bad" methods you showed actually will work very well indeed, and nothing that works as intended deserves to be called "bad." It's worthwhile pointing out that the "bad" methods you showed are how such things would be done in other languages, and that for someone coming to python from that language they are more easier read and understood than the python method. In each case, the python method *_might_* be better from a performance standpoint, but maybe not. Doing something in just one line instead of two, or avoiding the use of a single temporary variable, is--in a large number of cases--trivial and not worth the effort. Whether or not a method is "pythonic" also seems somewhat trivial, inasmuch as python is a full-blown language and can be used in a wide variety of ways. Doing something idiomatically in python has to be justified on more significant criteria than just that it's "pythonic."
Sebastiaan Mathôt (1 year ago)
+Todd Carney cannot disagree!
Angela Chika Ebirim (1 year ago)
That was excellent. Certainly learnt lots of tips along the way.
GoldPhoenix99 (1 year ago)
The code at 16:10 is not the most efficient. It's cool to know that the for loop has an else-catch all case... But this code is far more pythonic: if needle in haystack: print("Found.") else: print("Not found.")
Nick Andrievsky (1 year ago)
It worths to mention that solutions have trade-offs. For example, the first solution allocates ( or pools depends on implementation ) a new tuple on every iteration which effects performance. I believe adding implementation details and performance data could make your video more interesting and usefull. Here the performance test https://gist.github.com/andrievsky/ae2ffc13d67e3bd46e50040a148d4d8e
Nick Andrievsky (1 year ago)
You are correct and the performance is quite similar. Thank you for the reply.
Sebastiaan Mathôt (1 year ago)
Performance is indeed an important consideration. However, your benchmark script is comparing two different things: In the test with enumerate() you're keeping track of two counter variables (index and res), whereas in the test test without enumerate() you're keeping track of only one (res). Does that make sense? If you compare two pieces of code that are functionally equivalent, one with an one without enumerate(), you'll find that there is little to no performance difference.
asd asd (1 year ago)
So... is the Needle in the hay?
Zyepher (1 year ago)
Man this is so good
Rob Brown (1 year ago)
Which IDE is this please?
Rob Brown (1 year ago)
Great, thank you!
Sebastiaan Mathôt (1 year ago)
It's OpenSesame (https://osdoc.cogsci.nl/), an IDE for developing psychology and neuroscience experiments. But it's also perfectly useful for these kinds of Python demonstrations!
MARTIN SAGE (1 year ago)
Hey Check Out this code: Check = 5 Items = [1,2,3,4] print('Found!') if Check in Items else print('Not Found!')
Marcus Houtzager (1 year ago)
AI is making videos now
Roey Kelner (1 year ago)
What IDE is it?
Sebastiaan Mathôt (1 year ago)
+Roey Kelner this is OpenSesame, a semi-graphical development environment, mostly for neuroscience and psychology
Alex Ji (1 year ago)
I solve the Trick #6 by : if needle in haystack: print('Found!') else: print('Not found!')
Ryan Mcguinness (1 year ago)
It’s a great video but it had my coworker in tears laughing at how you where talking about “Getting Dick”.
Curtis Rawson (1 year ago)
Name of your Script Editor/Debugger?
Sebastiaan Mathôt (1 year ago)
+Curtis Rawson I'm using OpenSesame (http://osdoc.cogsci.nl/), an IDE for developing psychology and neuroscience experiments. But it's also perfectly suitable for these kinds of demonstrations!
chaitanya bangera (1 year ago)
x,y = y,x What sorcery is this!! :D
Ikem Krueger (1 year ago)
24:40 That is how context managers are implemented.
KeepYourRatOut (1 year ago)
Thanks Sebastiaan - very useful for a novice "Pythoner" :-)
Bballfan Mobile (1 year ago)
Great lesson 👍🏾, but please don't use "Dick" in anymore examples. 😆 😂 😂😂
Ken Haley (2 months ago)
Get your mind out of the gutter. "Dick" is a very common name. If you have a problem with it, it's your problem.
Jimmy Gunawan (1 year ago)
What IDE is this? Seems easy to use.
Sebastiaan Mathôt (1 year ago)
+Jimmy Gunawan it's OpenSesame, a semi-graphical IDE for developing neuroscience and psychology experiments.
Cheng Zheng (1 year ago)
Is this short code make the program run faster?
Sebastiaan Mathôt (1 year ago)
+Cheng Zheng for the most part, no. It's about readability.
Mort Kebab (1 year ago)
What is that IDE?
Jamie Bainbridge (1 year ago)
I don't think these make more readable code. It's not readable if you have to go look up the language reference to find out what zip() or tuple unpacking is or all corner cases of library functions like .get(). I don't disagree it's better to leverage language features but it makes the code non-obvious for people who don't know the language super well. For all this syntactic sugar you still use print format specifiers and not the Python 3 {0} or {var}. Being "Pythonic" is a bunch of vague elitist bullshit which assumes everyone has memorised the entire documentation and excludes those who haven't. Write code so it's plainly obvious to as many people as possible, even if that means it's a tad less efficient.
Deborah Freedman (1 year ago)
Better is a value judgement. In most of his examples, the "bad" code is much clearer, easier to read, and probably would be easier to debug. I think his 'good' code is extremely ugly and not as easy to understand. If he is going to write in this dense fashion, he needs to comment more. The only thing I agree with is the swap (#3) and using try: because it helps with exception handling. In #5, his 'good' is obvious, but Eliot's answer is more concise. For #6, I like an explicit open and close, because often I want to deal with specific I/O errors in a specific way to give the user a more meaningful error message
the_feature_selector (1 year ago)
Do these reduce compute as well or only a matter of style?
LoneTech (8 months ago)
They do help with performance. Particularly dict.get performs only one lookup, and with file ensures the file gets closed. for else uses an existing test (iteration ended) for more flexibility.
Sebastiaan Mathôt (1 year ago)
This is mostly about style, not computing performance!
Vincent Van Gogh (1 year ago)
great video! but don't encourage blank except lines
Sandy (1 year ago)
Dick is not in the dictionary because i have it on me
Uya78 İpek (1 year ago)
Good code does not mean shorter code. Zip function hurts PC more than akward code.
Rémi Lasvenes (1 year ago)
Font name ???
Maksim Huzmiev (1 year ago)
Did u put your keyboard on drum?
unbreakable footage (1 year ago)
how can 7 simple tricks be 25 minutes long
Jason Leach (1 year ago)
Gould, but could have been a bit shorter.
Carlos Contreras (1 year ago)
That was amazingly useful for me! Thank you Sebastian. I have coded in C for years, now entering at Python world I feel delighted for these shorcuts.
Evert de Boer (1 year ago)
Silly question maybe.. , but what development / testing environment is it that you use in this video? Thanx,, Sorry: already found the answer in the comments below.. 👍
True River (1 year ago)
the video from 19:47 onwards is a great explanation of the try statement and I think you could post this on its own. I also enjoyed the (unintentional?) pun at the end of the with statement when you say "and finally..." which is what you are moving on to.
Ruslan Kardashev (1 year ago)
I literally learned these solutions today reading the third part of the book called Learning Python. But thank you for demonstrating them:)
Ruslan Kardashev (1 year ago)
if dick in dictionary..
Artem Vasenin (1 year ago)
Is this just a rip off from this: https://www.youtube.com/watch?v=OSGv2VnC0go?
lalaland (1 year ago)
*Every* single tip in your video is copied from Raymond's presentation, even in the same order, and you *never* bothered even mentioning his talk. This is plagiarism, not inspiration.
Sebastiaan Mathôt (1 year ago)
Raymond Hettinger is definitely an inspiration for me, and that particular video is a must see for every Pythonista. Whether being inspired by and ripping off are the same thing—that I'll leave up to you.
Xin Zhao (1 year ago)
what IDE program you are using?
Sebastiaan Mathôt (1 year ago)
That's OpenSesame. It's a semi-graphical IDE for developing psychology and neuroscience experiments. But it's also perfectly useful for these kinds of demos!
Adam Cruickshank (1 year ago)
Surely zipping two lists is inefficient? The counter may be more lines, but isn't it quicker? Is the pythonic way to write less code regardless of performance?
True River (1 year ago)
Adam Cruickshank yes. It would aways run faster written in C and even faster in machine code. The Python way is to write most or all of it in elegant code and where code is seriously time consuming (like in a million iteration loop) hive that off into another language - that is whyPython makes it easy to call C C++ or machine code where you need to. So either way while writing in Python you are almost never thinking of speed over clarity.
Adam Cruickshank (1 year ago)
Sebastiaan Mathôt thanks for explaining. Python is new to me, but I come from a 30 year background of other languages. I read a bit more into it. As zip is an iterator, using in the loop means it's not physically combining the two lists. So as you say, efficient and elegant.
Sebastiaan Mathôt (1 year ago)
In most cases, zip is actually faster than using a counter. But the real gain is clarity of code!
Vaibhav Acharya (1 year ago)
If you wanna see hard then learn Java. 😂😂
LackBrain (1 year ago)
Don't know what tutorials I like best. The guys with the Mumbai accent or this Dutch guy?
Shortcut (1 year ago)
hey, een Hollander? Ok, ik probeer mezelf te leren programmeren, ik ben begonnen met HTML en CSS maar Javascript is zo... laat ons zeggen minder elegant. Dus ik denk dat ik beter af zal zijn als ik JS skip en direkt naar Python ga. Wat me enorm helpt als ik iets probeer te leren is humor, als ik eens moet lachen af en toe zijn de zenuwen ook minder waardoor ik me beter kan focussen op de taak, en alles blijft ook beter hangen in mijn hoofd dan.

Would you like to comment?

Join YouTube for a free account, or sign in if you are already a member.