TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Python Shortcuts for the Python Beginner

187 pointsby mburstover 12 years ago

21 comments

someone13over 12 years ago
Another method that I find isn't used enough: dict.setdefault. Instead of doing this:<p><pre><code> if 'key' in d: val = d['key'] else: val = d['key'] = 'some default value' </code></pre> You can do this:<p><pre><code> val = d.setdefault('key', 'some default value') </code></pre> This is super-useful for configuration in frameworks, for example - it's a one-liner to set a default config value if the user didn't provide one.
评论 #5123713 未加载
评论 #5125805 未加载
CodeMageover 12 years ago
Nice list. I only wish the author warned the readers that using the "get" method to get an item from the dictionary is not 100% equivalent to using try/except.<p>When using the method, the default value argument will always be evaluated, regardless of whether the dictionary key exists. If the expression that produces the default value is an expensive one or has side effects, the programmer might want to use the try/except variant instead.
shooover 12 years ago
Nice tips. One nitpick: the "inline if statement" is handy because it works as an expression, not just as a statement.<p>A few more useful things:<p>frozenset: immutable set values. these can be hashed, so you can use them as keys in dicts or put them in sets.<p>poor-man's transpose via zip:<p><pre><code> &#62;&#62;&#62; x = [('a', 'b'), ('c', 'd')] &#62;&#62;&#62; zip(*x) [('a', 'c'), ('b', 'd')] </code></pre> slices can be constructed with the "slice" function and passed around as values:<p><pre><code> &#62;&#62;&#62; f = lambda x, s : x[s] &#62;&#62;&#62; first3 = slice(3) &#62;&#62;&#62; last3 = slice(-3, None) &#62;&#62;&#62; rev = slice(None, None, -1) &#62;&#62;&#62; f('hello', first3) 'hel' &#62;&#62;&#62; f('hello', last3) 'llo' &#62;&#62;&#62; f('hello', rev) 'olleh'</code></pre>
shadowmatterover 12 years ago
Good list. My only thoughts:<p>Prefer itertools.izip instead of zip to avoid materializing a new list.<p>Appending the comma operator to the print statement suppresses the newline character and appends a space instead, which is how print 1, "world" works.<p>The only tip I'd add is using mapping keys in string formatting operations:<p><pre><code> &#62;&#62;&#62; d = {'cow': 'moo'} &#62;&#62;&#62; print 'the cow says %(cow)s' % d the cow says moo</code></pre>
评论 #5123914 未加载
评论 #5123821 未加载
cnlwsuover 12 years ago
I actually would prefer people on my team NOT use these shortcuts. For example:<p><pre><code> numbers = [1, 2, 3, 4, 5, 6] even = [] for number in numbers: if number % 2 == 0: even.append(number) </code></pre> is much easier to read and maintain imho then<p><pre><code> numbers = [1, 2, 3, 4, 5, 6] even = [number for number in numbers if number % 2 == 0] </code></pre> Also:<p><pre><code> for x in range(1,101):print"Fizz"[x%3*4:]+"Buzz"[x%5*4:]or x </code></pre> is a piece of code I never want someone else to write that I may someday have to maintain. Write it out the long way and make your teams lives easier.
评论 #5125512 未加载
评论 #5125812 未加载
verroqover 12 years ago
Slicing a list is not the same as taking subsets, the examples he provides are also misleading in this context.
gamegoblinover 12 years ago
Great post! For those who know Python, this may be common knowledge, but for the uninitiated, this is a great showcase of some simple ways that Python makes coding more intuitive and enjoyable.<p>You might also consider mentioning both dictionary and set comprehensions along with list comprehensions, as they are the exact same concept, yet even a lot of intermediate Python programmers don't know about them!
评论 #5123727 未加载
评论 #5123462 未加载
venomsnakeover 12 years ago
The last one is terrible ... I have seen<p>#define TRUE 0 #define FALSE 1<p>back in the day.<p>Too bad there was no source control in the company then, so I could not find out who was responsible for that travesty and "talk calmly" some sense into them.
评论 #5123671 未加载
评论 #5123844 未加载
bsaulover 12 years ago
Shouldn't "the last 3" be [-3:] instead of [3:] ? Inyour case it gives the correct result, but that's because your list has 6 elements i think. ( note : typing on my phone so i can't verify).
saurabhover 12 years ago
Don't forget itertools.product<p><a href="http://stackoverflow.com/questions/13885234/python-nested-looping-idiom" rel="nofollow">http://stackoverflow.com/questions/13885234/python-nested-lo...</a>
chmikeover 12 years ago
Could it be possible to explain what does<p><pre><code> Print "Fizz" [x%3*4::] </code></pre> Since range is going from 0 to 101 I have the impression the result won't match the directive.
评论 #5123643 未加载
评论 #5123659 未加载
gingerlimeover 12 years ago
nice list, agree with the other comments that the Fizzbuzz example is cool, but can be confusing to work out what it does, especially since this post is aimed at beginners.<p>I would also mention `getattr` similarly to `get`.
Scaevolusover 12 years ago
It's confusing that output is on the &#62;&#62;&#62; lines while input is not -- backwards from the REPL.<p>More things to consider: dict.iteritems, collections.defaultdict, enumerate(seq, 1)
sadmysqluserover 12 years ago
Somethings's up with your site. All I see are black boxes where your examples should be: <a href="http://imgur.com/N8vdzGX" rel="nofollow">http://imgur.com/N8vdzGX</a>
评论 #5123662 未加载
评论 #5123613 未加载
daGrevisover 12 years ago
Expression `False = True` reminds me of <a href="http://stackoverflow.com/a/771974/458610" rel="nofollow">http://stackoverflow.com/a/771974/458610</a>.
__sb__over 12 years ago
Are inline if statements considered good form? I rarely see them in use and I've heard people complain about them before.
nu2ycombinatorover 12 years ago
Very good list except the fizzbuzz example. It solves the problem but not easy to read, which is not python way.
klapinat0rover 12 years ago
Also good read for seasoned pythonistas, nice work, mburst
fijalover 12 years ago
you should always check the length of lists before zip, otherwise you end up with surprises (try running zip with unequal lengths)
chromejs10over 12 years ago
I didn't know about some of these. Nice!
Hyrum_Graffover 12 years ago
Sharing this with my AS Computer Science students. Very clear explanations.
评论 #5123691 未加载