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

7 Simple Tricks to Write Better Python Code

3976 ratings | 209151 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 (317)
ka totoy (2 days ago)
What software (IDE) is he using?
FreeFly (2 days ago)
For the first example, can't you use enumerate?
Rich Plewa (13 days 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 (17 days ago)
Thanks a lot :)
mike lee (1 month ago)
Great video! super helpful!
Илья Иванов (1 month 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 (2 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 (2 months ago)
I realized you were Dutch after seeing Amsterdam in your list.
Sushant Kulkarni (3 months ago)
The good way for finding an element in a list could have been haystack.__contains__(needle), don't you think?
Sushant Kulkarni (3 months ago)
10:00 one can never be a 100% sure whether...
Zeling Kuang (3 months ago)
Great video! Thanks a lot! And I'm wondering which IDE do you use in this video?
Zeling Kuang (3 months ago)
Sebastiaan Mathôt  Ok, Thank you!
Sebastiaan Mathôt (3 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 (3 months ago)
at 14.49 why not do 'if letter in haystack: print('found') else: print('Not found!')
Siya Busakwe (3 months ago)
Put Dick in the dictionary
ddstar (3 months ago)
20 minutes too long
Stanly (3 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 (3 months ago)
excellent
Vady (4 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 (5 months ago)
Excellent tips, great audio and pace, thanks so much!
Aleksandr Saint (5 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 (6 months ago)
Thanks 😊
J MacKay (6 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
Na No (6 months ago)
Hehe, Dick.
Surfer (6 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 (6 months ago)
There is a typo: if ('Dick' in ages) . You mispelt "Agnes". You're welcome.
The Academy (6 months ago)
Thank you for a good video!
GallingGamer (7 months ago)
"The pythonic way" thanks, stack overflow... no but forreal very helpful video that phrase is just overused and obnoxious.
LordCucumber77 (7 months ago)
You should look up Dick in the Dictionary. But seriously, thanks for the tips! Useful!
M M (7 months ago)
Love the O.G. reference haha. Grandfather of gangster rap 💯
Clint Sullivan (7 months ago)
https://gist.github.com/clsulli/104c74512b5988d4b4ff105a5c3189b7
Sebastiaan Mathôt (7 months ago)
Awesome, thank you!
Almatik Dayanchik (7 months ago)
What kind of text editor do u use ?
Green Eggs and Ham (7 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 (7 months ago)
umm or for i in range(0, len(cities)): print(' the city :', i ,cities[i])
Green Eggs and Ham (7 months ago)
...ahh he wanted a counter printed too
Marwan Ghubein (7 months ago)
Very useful and informative
R (7 months ago)
I love your keyboard noises. Adds that kind of warmth to it
JK FRT (8 months ago)
Thanks, great video, good tips. Made me rethink a bunch of things from my current project.
cheuch (8 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 (8 months ago)
KeyError dick :DD
Chao Zen (8 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 (8 months ago)
Die Hollanders toch he
hrishi chandanpurkar (8 months ago)
What IDE is that??
Sebastiaan Mathôt (8 months ago)
+hrishi chandanpurkar it's OpenSesame (https://osdoc.cogsci.nl/), an IDE for developing psychology/ neuroscience experiments.
Mengfei Li (8 months ago)
Great lecture, thank you.
guh (9 months ago)
dick
Ere bos (9 months 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 (4 months ago)
that last line is possible? :O
zeppelin0110 (9 months ago)
Learned a few new things, for sure
Prog Nauts (9 months ago)
Thanks, your tutorials are so well explained..
Keijo228 (10 months ago)
11:25 I can't get how did you put lines in comments?
Sebastiaan Mathôt (10 months 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 (10 months 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 (10 months ago)
+Todd Carney cannot disagree!
Angela Chika Ebirim (10 months ago)
That was excellent. Certainly learnt lots of tips along the way.
GoldPhoenix99 (10 months 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 (11 months 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 (10 months ago)
You are correct and the performance is quite similar. Thank you for the reply.
Sebastiaan Mathôt (11 months 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 (11 months ago)
So... is the Needle in the hay?
Zyepher (11 months ago)
Man this is so good
Rob Brown (11 months ago)
Which IDE is this please?
Rob Brown (11 months ago)
Great, thank you!
Sebastiaan Mathôt (11 months 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. 😆 😂 😂😂
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 (5 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.
Danny Dai (1 year ago)
they are useful. thanks
Aleksandar Krumov (1 year ago)
I hate your keyboard noises.
Daniel Dias (1 year ago)
the finally runs it you return in try or except?
Sebastiaan Mathôt (1 year ago)
Yes it does!
bbb - (1 year ago)
great tips Sebastian, thanks. do you have anything on unittest or pytest, how to do TDD with python the easy way?
Sebastiaan Mathôt (1 year ago)
I don't but it might be a good topic for a next video. I personally use nose and Python's built-in unittest (for different projects). py.test looks interesting as well though.
Peng Qian (1 year ago)
thx for the video. I took a half year course on python before and now i'm trying to get back some of the old memories. this really helps with my coding readability.
Amir Abu Jandal (1 year ago)
excellent stuff. worth watching. many thanks :) :)
Merveille van Eck (1 year ago)
tip no. 1: Dont code in windows
iWonderOfficial (1 year ago)
For the cities list example, I wonder how the following compares to your enumerate solution: for i in range(0, len (cities)): Print(i, cities[i]) Is there a downside to doing it this way? To me, it seems more readable, but perhaps there is a performance downside? Looking forward to answers! :)
Sebastiaan Mathôt (1 year ago)
Yes, that accomplishes the exact same thing, but less elegantly!
ΓΙΑΝΝΗΣ (1 year ago)
IS BASHING YOUR KEYBOARD NEXT TO YOUR MIC, THE PYTHONIC WAY???
Ed Kern (4 days ago)
def answer(computer): if computer.type == "Laptop": return("yes") return("no")
Khalid Al-Dosari (5 months ago)
you got me
Dan Rassler (1 year ago)
Explicit is better than implicit.
Ricardo Equisyezeta (1 year ago)
Excuse me, what IDE are you using?
Ricardo Equisyezeta (1 year ago)
Sebastiaan Mathôt Thanks for the info
Sebastiaan Mathôt (1 year ago)
That's OpenSesame (http://osdoc.cogsci.nl/), an IDE specifically for developing neuroscience/ psychology experiments. But it's also a perfectly adequate editor for these kinds of demonstrations.
john mcmanus (1 year ago)
dude your keyboard sounds like war drums
Sebastiaan Mathôt (1 year ago)
The editor is my battlefield.
Shadow Lurker (1 year ago)
Pimpin ain't easy ( ͡° ͜ʖ ͡°)

Would you like to comment?

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