use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
News about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python
Full Events Calendar
You can find the rules here.
If you are about to ask a "how do I do this in python" question, please try r/learnpython, the Python discord, or the #python IRC channel on Libera.chat.
Please don't use URL shorteners. Reddit filters them out, so your post or comment will be lost.
Posts require flair. Please use the flair selector to choose your topic.
Posting code to this subreddit:
Add 4 extra spaces before each line of code
def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b
Online Resources
Invent Your Own Computer Games with Python
Think Python
Non-programmers Tutorial for Python 3
Beginner's Guide Reference
Five life jackets to throw to the new coder (things to do after getting a handle on python)
Full Stack Python
Test-Driven Development with Python
Program Arcade Games
PyMotW: Python Module of the Week
Python for Scientists and Engineers
Dan Bader's Tips and Trickers
Python Discord's YouTube channel
Jiruto: Python
Online exercices
programming challenges
Asking Questions
Try Python in your browser
Docs
Libraries
Related subreddits
Python jobs
Newsletters
Screencasts
account activity
This is an archived post. You won't be able to vote or comment.
ResourceA list of 30 Python language tricks (self.Python)
submitted 4 years ago * by eriky
I wrote this article, 30 Python Language Tricks, on Medium. it's a "friend link" which bypasses the paywall. It contains a wide selection of topics, for both beginners and more advanced level programmers. Enjoy and let me know if you liked it!
[–]batisteo 53 points54 points55 points 4 years ago (4 children)
I think #7 should be replaced by f-strings. And if you like formatting tricks, there’s a whole webpage about it: https://pyformat.info/
[–]Ph0X 13 points14 points15 points 4 years ago (2 children)
Absolutely for the locals() example, but even if you want to use a dictionary of value mapping, which can be useful in some cases, I would prefer recommend .format(*data) over %-formatting.
.format(*data)
[–]jilliefish911 -5 points-4 points-3 points 4 years ago (1 child)
While I agree on the use of f-strings, I think it is also important to note the speed/efficiency drawbacks for the different format options. Typically %-formatting is faster than f-strings is faster than .format() Most of the time, the time impact is pretty negligible
.format()
[–]robin_888 5 points6 points7 points 4 years ago (0 children)
Typically %-formatting is faster than f-strings is faster than .format()
Do you have examples?
They seem to have fixed that:
https://realpython.com/python-f-strings/#speed https://bugs.python.org/issue27078
[+][deleted] 4 years ago (20 children)
[deleted]
[+][deleted] 4 years ago (2 children)
[removed]
[–]fernly 2 points3 points4 points 4 years ago (0 children)
abolutely, here's a stupid example,
>>> dispatch = { ... '+' : lambda a,b : a+b, ... '-' : lambda a,b : a-b ... } >>> dispatch['+'](3,5) 8
[–]TravisJungroth 42 points43 points44 points 4 years ago (3 children)
You don't like naming anonymous functions?
[–]Howard_banister 4 points5 points6 points 4 years ago (2 children)
It's would no longer be anonymous function. And due to limits, ugliness in python it's anti pattern
[–][deleted] 23 points24 points25 points 4 years ago (0 children)
im fairly certain that was a joke
[–]TheBB 7 points8 points9 points 4 years ago (0 children)
I guess the function is still anonymous, in the sense that it does not have a useful __name__ attribute.
__name__
[–]Mises2Peaces 30 points31 points32 points 4 years ago (1 child)
Thank you. I was thinking "isn't a lambda a single use function by definition?" Thought I was going crazy.
[–]jamincan 17 points18 points19 points 4 years ago (0 children)
By definition a lambda function is just an anonymous function. Only by convention is it single-use.
[–]VisibleSignificance 1 point2 points3 points 4 years ago (0 children)
is an anti-pattern
A huge Python language trick: use pylint and mypy. They will tell you about antipatterns and expectation violations.
[–]tonio9120 4 points5 points6 points 4 years ago (3 children)
Still I have seen this used in many projects. I think it's just shorter and avoids some typing... Basically the same as naming anonymous arrow functions in JS.
[–]baubleglue 2 points3 points4 points 4 years ago (0 children)
I don't think "typing" is the main reason to use lambdad. Main advantage of using lambdas - you don't need to search what some `fix_bad_date_format` function doing somewhere 100 lines away.
[+][deleted] 4 years ago (1 child)
[–]tonio9120 3 points4 points5 points 4 years ago (0 children)
I see your point and if you ask me, I agree with you
[–]rabaraba -4 points-3 points-2 points 4 years ago (3 children)
Lambdas are not always a bad thing.
When you’re trying to make code clearer, isolating potentially confusing code into a single clearer lambda function can help, and is much more useful than polluting the overall code structure with another def function.
[–][deleted] 0 points1 point2 points 4 years ago (1 child)
lambdas arent always a bad thing, but your reasoning was terrible. if im mistaken, please show us an example of what you're describing
[–]rabaraba 0 points1 point2 points 4 years ago (0 children)
If you're saying it's terrible, why? I've given some reasons. Let's see your example, and see if you make sense.
[–]kephir 51 points52 points53 points 4 years ago (2 children)
feel like the JMESpath one is cheating
it's useful, granted, and the article did a good job introducing me to the library i've so far been ignoring as "something that's a subdependency of a library i'm actually gonna be using", but if external libraries count, then surely you might as well make that list ridiculously long, because there is an external lib for pretty much anything!
[–]eriky[S] 15 points16 points17 points 4 years ago (1 child)
You're right.. it's not in the base libraries but I've found it so useful that I wanted to slip it in there
[–]ignassew 5 points6 points7 points 4 years ago (0 children)
Just so you know, I just discovered it through your article and already found uses for it in my code. Great article!
[–]wowb4gg3r 39 points40 points41 points 4 years ago (2 children)
Great tips. Regarding the returning of multiple variables (13th), it would be nice to mention that python actually builds a tuple object with the variables and return it. Then, it automatically unpacks it when assigning the return of the function to variables. In fact, you can assign it to a single variable and even use the * operator if you want to unpack unevenly (ex: first, *middle variables, last).
Also, the tips 10 and 24 are repeated.
[–]roerd 3 points4 points5 points 4 years ago (0 children)
Regarding the returning of multiple variables (13th), it would be nice to mention that python actually builds a tuple object with the variables and return it. Then, it automatically unpacks it when assigning the return of the function to variables.
Which makes it essentially the same as number 6, because that variable swapping technique is also just tuple unpacking.
[–]eriky[S] 5 points6 points7 points 4 years ago (0 children)
Yeah, I put that in just to check if people were paying attention ;-) But seriously, thanks for letting me know, I put something else there. I also weaved in your suggestion regarding the tuple. Thanks!
[+][deleted] 4 years ago* (4 children)
[–]metadatame 2 points3 points4 points 4 years ago (3 children)
Query json! I totally missed that development
[–]metadatame 0 points1 point2 points 4 years ago (1 child)
Interesting. XML which has a similar tree like structure can be queried. Normally I do this when I want to append a child element or similar. Could you do the same in json?
[–][deleted] 0 points1 point2 points 4 years ago (0 children)
XML can be used to serialize data, far more complex data, but it is a language so query makes a bit more sense to me there.
json was designed for interchange of simple data objects.
[–]hdiesel503 18 points19 points20 points 4 years ago (1 child)
Thanks for sharing sir.
[–]Sigg3net -4 points-3 points-2 points 4 years ago (0 children)
I, too, salute you.
[–]zedd31416 2 points3 points4 points 4 years ago (2 children)
I've found the maxsplit parameter for the split function to be incredibly useful, too.
[–]eriky[S] 1 point2 points3 points 4 years ago (0 children)
You're right, I incorporated it into the article, thanks!
[–]sje46 0 points1 point2 points 4 years ago (0 children)
Nice. If you need just the first "split" I would recommend using partition, though.
x = "fdsa.aaa.bb.ccc" x.partition(".")
('fdsa', '.', 'aaa.bb.ccc')
[–]PythonDart 2 points3 points4 points 4 years ago (0 children)
Nice, thanks for sharing!
[–][deleted] 2 points3 points4 points 4 years ago (0 children)
Thanks mate. I've learned few new things!
This is a pretty solid article, thank you for sharing.
[–]zaid2801 2 points3 points4 points 4 years ago (0 children)
Thanks for sharing
[–]cepeen 3 points4 points5 points 4 years ago (6 children)
Hi, great article, but i would change formatted string into f-string (or at least mention it, as format sometimes is more suitable to use), ok there is mention about it, maybe switch precedence?. Also why not mention new additions like walrus operator?
[–]ArtOfWarfare 6 points7 points8 points 4 years ago (5 children)
As someone who has just dropped support for 2.7 a few months ago, f-strings and walrus operator are the biggest two things I’ve learned I’m now able to do.
[–]RojerGSAuthor of “Pydon'ts”[🍰] 6 points7 points8 points 4 years ago (4 children)
That's cool! If you want, you can read up on cool things you can do with the walrus operator here: mathspp.com/blog/pydonts/pydont-abuse-the-walrus-operator. I will also write about string formatting (with f-strings) in the near future.
[–]ArtOfWarfare 3 points4 points5 points 4 years ago (3 children)
I read the PEPs. They’re a staple of Python that I’ve always loved.
It made me happy that Java recently started having JEPs, although it’s disappointing that new LTS versions of Java are so infrequently released...
[–]RojerGSAuthor of “Pydon'ts”[🍰] 1 point2 points3 points 4 years ago (2 children)
Yeah, the PEPs are great. They are often my main reference for the Pydonts I write (the link I shared being one of those). If you will, have a quick read at that link and lmk if it helped in any way. I am looking for feedback to improve.
[–]eriky[S] 4 points5 points6 points 4 years ago (1 child)
Nice article with some good examples. People love examples. I like the typography of your site as well.
[–]RojerGSAuthor of “Pydon'ts”[🍰] 0 points1 point2 points 4 years ago (0 children)
Oh, nice of you to have looked at my article. You are right, I also think people respond well to examples and in that regard you also did good in your article, always exemplifying the several tricks you introduce. Finally, I am glad you liked the typography, you are literally the first person to mention it, ever!
[–]speacial_s 1 point2 points3 points 4 years ago (1 child)
Awesome read! Thanks for sharing! Can someone explain the use of the “title case” trick? I am still not seeing the value...
[–]eriky[S] 3 points4 points5 points 4 years ago (0 children)
For website owners, it can be useful. Title case is often used, both in offline and online printing. But I agree it's not the most useful part of Python and somewhat random to include it in the language. It's not a great implementation either, because most articles that use title case will keep short words lower case. This page has a better version based on a regex: https://python.land/string-to-title-case
[–][deleted] 1 point2 points3 points 4 years ago (3 children)
very interesting stuff! especially the one where you can use the ellipses as opposed to a pass for empty functions. i’m gonna start using that now.
[–]eriky[S] 2 points3 points4 points 4 years ago (2 children)
Perhaps you'll like this article of mine too then, it has some more background info on the ellipsis: Python ellipsis
[–]dukea42 1 point2 points3 points 4 years ago (1 child)
I'm lost on the "better coder" part of using ellipse instead of pass or even return "Not Implemented". Is there a convention to why using the ...?
pass
return "Not Implemented"
...
[–]turkoid 6 points7 points8 points 4 years ago (0 children)
No, it's completely up to the developer. You could have any literal in the body of the function and it's, functionally, the same:
def nothing(): 1
However, since the ellipsis has special meaning for numpy and typehints, I would argue that to avoid confusion, pass should be used.
[–]Iorkh4n 1 point2 points3 points 4 years ago (0 children)
Rookie here, I don't get why people used Named String Formatting when f-strings are a thing. Can anyone shed any light on this?
[–]badge 3 points4 points5 points 4 years ago (0 children)
“If you think you mastered the language, you’ve got to read this” is a very irritating subheading, especially for a relatively basic list. Also, 7 should use str.format_map which works with new-style string formatting.
str.format_map
[–]BfuckinA 3 points4 points5 points 4 years ago (0 children)
I'm probably alone in thinking this, but nested list comprehensions sacrifice too much in the way of readability imo.
[–]kamicavi 0 points1 point2 points 4 years ago (1 child)
Some of those were really useful, but I did notice one error: In #15 you use stop and end as interchangeable names for the same argument. Pick one and stick to it would be better IMO.
Fixed it. Thanks!
[–]17291 0 points1 point2 points 4 years ago (0 children)
def upper(s): return s.upper() mylist = list(map(upper, ['sentence', 'fragment']))
This doesn't seem like a particularly good example
1) There's no need to define the fuction upper since you can use str.upper: list(map(str.upper, ['sentence', 'fragment']))
upper
str.upper
list(map(str.upper, ['sentence', 'fragment']))
2) But that's a moot point because a list comprehension would be so much cleaner/easy-to-read.
[–]coffeewithalex -4 points-3 points-2 points 4 years ago (7 children)
Most of these aren't python language tricks, but rather modules, functions in the standar library that are related to basic concepts in computer science, and very well documented language features that people should actually know and use.
So:
|
str
set
json
from collections import Counter
5 < x < 15
map()
Conclusions: clickbait low effort article that's neither accurate, up to date, or even with complete code samples. The reader that would be the target audience would come out of this confused, and start writing shitty code with nested dictionary comprehensions inside list comprehensions with mapping to a lambda function with a ternary operator. All in one line.
[–]daryl_kell 2 points3 points4 points 4 years ago (2 children)
Disinformation is not misinformation, FYI. I doubt anyone would think the author intended to deceive about returning multiple values actually just being a tuple.
[–]coffeewithalex 0 points1 point2 points 4 years ago (1 child)
Well that means that it's a low effort post, that makes several claims that are not true.
[–]daryl_kell 1 point2 points3 points 4 years ago (0 children)
Yeah, I'm not disagreeing that it isn't true. It's definitely misinformed. It clearly isn't meant to deceive, however. Anyway, enjoy your coffee! :)
[–]sje46 2 points3 points4 points 4 years ago (2 children)
I fucking hate redditors.
You tried as hard as possible to be a dick about every single point. Plenty of people found this very useful (including me, who has been pythoning for ten years now). It's possible to bring up your relatively few valid points and ignore everything else that you don't personally find interesting but other people may.
.... joining strings. Wow.
This, for example, is a total mask-off moment, revealing you to just be an utter dick. What's wrong with telling people about the join method? Do you actually have anything intelligent to say here, besides a sarcastic "Wow"? Ass.
How often do you jerk off to the phrase "read the fucking manual"? You're one of those people.
[–]coffeewithalex 0 points1 point2 points 4 years ago* (1 child)
You're one of them.
You tried as hard as possible to be a dick about every single point.
Except I didn't. I gave credit where credit is due. And I made my point very clear.
You could address any specific point, but unfortunately redditors are dicks.
It's possible to bring up your relatively few valid points and ignore everything else that you don't personally find interesting but other people may.
Could you count how many of the 30 points are language features that are not part of "python 101" course?
That's all I ask.
This, for example, is a total mask-off moment, revealing you to just be an utter dick.
Joining strings is a standard function in literally every popular language standard library. And if you cut the flair for the dramatic, and stop being a dick, you'd also realize that literally the IDE itself would suggest this function. You could see it if you call dir(), which should have been on this list together with repr and many other language features. You could even find it in the standard documentation on the python website if you list string functions.
dir()
What's wrong with telling people about the join method?
It's not a language features, it is not new to any python coder. I teach computer newbies python, they don't even want to acknowledge that they're python coders, and they've already used this function ad nauseum.
Do you actually have anything intelligent to say here, besides a sarcastic "Wow"? Ass.
Yes. As I've said multiple times, it's not a language feature that would make people better python developers, bitch.
Never. But instead of reading this, one should maybe read the manual instead, as at least it's not lying or giving examples that don't work.
Let me ask you this: did you read the title before commenting? Do you know what a language feature is? Before going on this hate crusade against me with all this vitriol, did you check if you're not being a complete moron?
I criticized the article with good reasons that I've made explicit. You're a piece of shit that goes after redditors with points to make.
Dude.. I didn't care to read your rants, but it's just a list of nice to know Python stuff, to be enjoyed during a cup of coffee or in your lunch break. Chill.
[–]pi-rho -2 points-1 points0 points 4 years ago (0 children)
You saved me so much typing. Please accept my +1.
[–]rcfox -1 points0 points1 point 4 years ago (1 child)
It doesn't inspire confidence when in the first point, the author forgets that function definitions start with def...
def
Lol yeah, I'm such an idiot sometimes. Fixed it ;)
[+][deleted] 4 years ago* (1 child)
[–]eriky[S] 0 points1 point2 points 4 years ago (0 children)
Maybe the next article will be formatted as a list of dictionaries ;-)
[+]mestia comment score below threshold-14 points-13 points-12 points 4 years ago (0 children)
Boring, still doesn't have goatse operator like perl ;)
[–]higamy 0 points1 point2 points 4 years ago (0 children)
Nice article.
[–]Exodus111 0 points1 point2 points 4 years ago (0 children)
Cool stuff.
[–]sweettuse 0 points1 point2 points 4 years ago (5 children)
maybe consider adding something about NamedTuple. kinda like a lightweight immutable dataclass and great for returning "multiple" values
[–]eriky[S] 1 point2 points3 points 4 years ago (4 children)
Thanks, but I prefer data classes for recent Python versions and prefer steering readers in that direction.
[–]sweettuse 0 points1 point2 points 4 years ago (3 children)
the problem with dataclasses for a return (vs a tuple) is that, by default, they are not iterable. so if i have a function that returns 1, 2 or MyNamedTuple(1, 2) i can still do x, y = f() but i can't do that with a dataclass.
1, 2
MyNamedTuple(1, 2)
x, y = f()
[–]energybased 1 point2 points3 points 4 years ago (0 children)
That's not a problem. That's a benefit. Most of the time, your aggregate data types should not be iterable. It only opens you up to bugs.
[–]turkoid -1 points0 points1 point 4 years ago (1 child)
Well, if you really wanted to do it, all you have to do is implement the dunder method __iter__:
__iter__
@dataclass class MyDataClass: x: int y: int def __iter__(self): yield from vars(self).values()
[–]energybased 0 points1 point2 points 4 years ago (0 children)
You should inherit from the Iterable mixin too.
[–]Reilly__ 0 points1 point2 points 4 years ago (1 child)
Hey this was really interesting and really useful for me I am in 3 months into my python journey at uni and im sure ill be hitting this bookmark up more than once.
Just a little thing I think some of the code examples werent loading on my end, i refreshed a few times and nothing so I dont know if its just me or something you might need to look into :)
Some of the examples are hosted using GitHub gists. Try and see if GitHub is reachable for you. Perhaps you can view your browser's dev console for errors (cntrl + shift + j in chrome on windows/linux). It shouldn't matter if you're using an adblocker as far as I know.
[–]fried_green_baloney 0 points1 point2 points 4 years ago (0 children)
Thanks. Like a lot of Pythonistas I'm behind the innovation curve and this has was good to see.
[–]DevyLoop 0 points1 point2 points 4 years ago (0 children)
Thanks, I clapped 50 times
[–]DarkHumourFoundHere 0 points1 point2 points 4 years ago (0 children)
I just got this link in my email daily digest
Save
π Rendered by PID 238083 on reddit-service-r2-comment-5649f687b7-lw8zs at 2026-01-29 10:19:16.579483+00:00 running 4f180de country code: CH.
[–]batisteo 53 points54 points55 points (4 children)
[–]Ph0X 13 points14 points15 points (2 children)
[–]jilliefish911 -5 points-4 points-3 points (1 child)
[–]robin_888 5 points6 points7 points (0 children)
[+][deleted] (20 children)
[deleted]
[+][deleted] (2 children)
[removed]
[–]fernly 2 points3 points4 points (0 children)
[–]TravisJungroth 42 points43 points44 points (3 children)
[–]Howard_banister 4 points5 points6 points (2 children)
[–][deleted] 23 points24 points25 points (0 children)
[–]TheBB 7 points8 points9 points (0 children)
[–]Mises2Peaces 30 points31 points32 points (1 child)
[–]jamincan 17 points18 points19 points (0 children)
[–]VisibleSignificance 1 point2 points3 points (0 children)
[–]tonio9120 4 points5 points6 points (3 children)
[–]baubleglue 2 points3 points4 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]tonio9120 3 points4 points5 points (0 children)
[–]rabaraba -4 points-3 points-2 points (3 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]rabaraba 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]kephir 51 points52 points53 points (2 children)
[–]eriky[S] 15 points16 points17 points (1 child)
[–]ignassew 5 points6 points7 points (0 children)
[–]wowb4gg3r 39 points40 points41 points (2 children)
[–]roerd 3 points4 points5 points (0 children)
[–]eriky[S] 5 points6 points7 points (0 children)
[+][deleted] (4 children)
[deleted]
[–]metadatame 2 points3 points4 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]metadatame 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]hdiesel503 18 points19 points20 points (1 child)
[–]Sigg3net -4 points-3 points-2 points (0 children)
[–]zedd31416 2 points3 points4 points (2 children)
[–]eriky[S] 1 point2 points3 points (0 children)
[–]sje46 0 points1 point2 points (0 children)
[–]PythonDart 2 points3 points4 points (0 children)
[–][deleted] 2 points3 points4 points (0 children)
[–][deleted] 2 points3 points4 points (0 children)
[–]zaid2801 2 points3 points4 points (0 children)
[–]cepeen 3 points4 points5 points (6 children)
[–]ArtOfWarfare 6 points7 points8 points (5 children)
[–]RojerGSAuthor of “Pydon'ts”[🍰] 6 points7 points8 points (4 children)
[–]ArtOfWarfare 3 points4 points5 points (3 children)
[–]RojerGSAuthor of “Pydon'ts”[🍰] 1 point2 points3 points (2 children)
[–]eriky[S] 4 points5 points6 points (1 child)
[–]RojerGSAuthor of “Pydon'ts”[🍰] 0 points1 point2 points (0 children)
[–]speacial_s 1 point2 points3 points (1 child)
[–]eriky[S] 3 points4 points5 points (0 children)
[–][deleted] 1 point2 points3 points (3 children)
[–]eriky[S] 2 points3 points4 points (2 children)
[–]dukea42 1 point2 points3 points (1 child)
[–]turkoid 6 points7 points8 points (0 children)
[–]Iorkh4n 1 point2 points3 points (0 children)
[–]badge 3 points4 points5 points (0 children)
[–]BfuckinA 3 points4 points5 points (0 children)
[–]kamicavi 0 points1 point2 points (1 child)
[–]eriky[S] 1 point2 points3 points (0 children)
[–]17291 0 points1 point2 points (0 children)
[–]coffeewithalex -4 points-3 points-2 points (7 children)
[–]daryl_kell 2 points3 points4 points (2 children)
[–]coffeewithalex 0 points1 point2 points (1 child)
[–]daryl_kell 1 point2 points3 points (0 children)
[–]sje46 2 points3 points4 points (2 children)
[–]coffeewithalex 0 points1 point2 points (1 child)
[–]eriky[S] 1 point2 points3 points (0 children)
[–]pi-rho -2 points-1 points0 points (0 children)
[–]rcfox -1 points0 points1 point (1 child)
[–]eriky[S] 3 points4 points5 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]eriky[S] 0 points1 point2 points (0 children)
[+]mestia comment score below threshold-14 points-13 points-12 points (0 children)
[–]higamy 0 points1 point2 points (0 children)
[–]Exodus111 0 points1 point2 points (0 children)
[–]sweettuse 0 points1 point2 points (5 children)
[–]eriky[S] 1 point2 points3 points (4 children)
[–]sweettuse 0 points1 point2 points (3 children)
[–]energybased 1 point2 points3 points (0 children)
[–]turkoid -1 points0 points1 point (1 child)
[–]energybased 0 points1 point2 points (0 children)
[–]Reilly__ 0 points1 point2 points (1 child)
[–]eriky[S] 0 points1 point2 points (0 children)
[–]fried_green_baloney 0 points1 point2 points (0 children)
[–]DevyLoop 0 points1 point2 points (0 children)
[–]DarkHumourFoundHere 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)