Python Shortcuts for the Python Beginner (Posted on January 26th, 2013)
The following are just a collection of some useful shortcuts and tools I've found in Python over the years. Hopefully you find them helpful.
Swapping Variables
x = 6 y = 5 x, y = y, x print x >>> 5 print y >>> 6
Inline if Statement
print "Hello" if True else "World" >>> Hello
Concatenations
The last one is a pretty cool way to combine objects of two different types.
nfc = ["Packers", "49ers"] afc = ["Ravens", "Patriots"] print nfc + afc >>> ['Packers', '49ers', 'Ravens', 'Patriots'] print str(1) + " world" >>> 1 world print `1` + " world" >>> 1 world print 1, "world" >>> 1 world print nfc, 1 >>> ['Packers', '49ers'] 1
Number Tricks
#Floor Division (rounds down) print 5.0//2 >>> 2 #2 raised to the 5th power print 2**5 >> 32
Be careful with division and floating point numbers.
print .3/.1 >>> 2.9999999999999996 print .3//.1 >>> 2.0
Numerical Comparison
This is a pretty cool shortcut that I haven't seen in too many languages.
x = 2
if 3 > x > 1:
print x
>>> 2
if 1 < x > 0:
print x
>>> 2
Iterate Through Two Lists at the Same Time
nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
print teama + " vs. " + teamb
>>> Packers vs. Ravens
>>> 49ers vs. Patriots
Iterate Through List With an Index
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
print index, team
>>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots
List Comprehension
With a list comprehension we can turn this:
numbers = [1,2,3,4,5,6]
even = []
for number in numbers:
if number%2 == 0:
even.append(number)
Into this:
numbers = [1,2,3,4,5,6] even = [number for number in numbers if number%2 == 0]
Pretty sweet huh?
Dictionary Comprehension
Similar to the list comprehension we can also do a dictionary comprehension like this:
teams = ["Packers", "49ers", "Ravens", "Patriots"]
print {key: value for value, key in enumerate(teams)}
>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}
Initialize List Values
items = [0]*3 print items >>> [0,0,0]
Converting a List to a String
teams = ["Packers", "49ers", "Ravens", "Patriots"] print ", ".join(teams) >>> 'Packers, 49ers, Ravens, Patriots'
Get Item From Dictionary
I'll admit that try/except code doesn't look the prettiest. Here's a simple way to fix that with dictionaries. This will try to find the key in the dictionary and if it can't be found it will set the variable to the second parameter.
Instead of:
data = {'user': 1, 'name': 'Max', 'three': 4}
try:
is_admin = data['admin']
except KeyError:
is_admin = False
Do this:
data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = data.get('admin', False)
Taking a Subset of a List
Sometimes you only want to run code over a portion of a list. Here are a few ways you can get the subset of a list.
x = [1,2,3,4,5,6] #First 3 print x[:3] >>> [1,2,3] #Middle 4 print x[1:5] >>> [2,3,4,5] #Last 3 print x[-3:] >>> [4,5,6] #Odd numbers print x[::2] >>> [1,3,5] #Even numbers print x[1::2] >>> [2,4,6]
FizzBuzz in 60 Characters
A while back Jeff Atwood popularized a simple programming exercise called FizzBuzz. Here is the excerpt on the problem:
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
Here's a short, fun way to solve the problem.
for x in range(1,101):print"Fizz"[x%3*4:]+"Buzz"[x%5*4:]or x
Collections
In addition to python's built in datatypes they also include a few extra for special use cases in the collections module. I find the Counter to be quite useful on occasion. Some of you may even find it useful if you're participating in this year's Facebook HackerCup.
from collections import Counter
print Counter("hello")
>>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Itertools
Along with the collections library python also has a library called itertools which has really cool efficient solutions to problems. One is finding all combinations. This will tell us all the different ways the teams can play each other.
from itertools import combinations
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
print game
>>> ('Packers', '49ers')
>>> ('Packers', 'Ravens')
>>> ('Packers', 'Patriots')
>>> ('49ers', 'Ravens')
>>> ('49ers', 'Patriots')
>>> ('Ravens', 'Patriots')
False == True
This is more of a fun one than a useful technique. In python True and False are basically just global variables. Thus:
False = True
if False:
print "Hello"
else:
print "World"
>>> Hello
If you've got any other cool tips/tricks leave them in the comments below. Thanks for reading!
Tags: Python
Comments:
Juho Vepsäläinen - 3 months, 3 weeks ago
A couple to add: sets, yield, decorators, functools. functools in particular contains some powerful functions such as partial. Good list overall.
trout - 3 months, 3 weeks ago
It might be a good idea to mention falsy values like [], '', etc that are pretty useful/make code a bit more elegant when writing loops, conditionals.
Amir Rachum - 3 months, 3 weeks ago
I've written a blog post about this exact issue! http://blog.amir.rachum.com/post/30176371115/you-cant-handle-the-truth
allo - 3 months, 2 weeks ago
You're having a Problem with "if x is not None". You need to use "if not x is None", because ... x=True if x is not None: __ print "bla"
allo - 3 months, 2 weeks ago
argh, it kills all whitespace, even linebreaks. So, just try on python shell, what "not None" is. Its True, so if you're testing for "x is not None", you're testing for "x is True", which even succeeds if x == True, because True is a global contstant object in python.
Halex - 3 months, 3 weeks ago
Your fizzbuzz code prints numbers starting with 0 to 100 instead of 1 to 100, so you have to add 2 characters and change "range(101)" to "range(1,101)" but the 2 characters can later be omitted by removing the last ":" in the two slices, i.e "[x%3*4:]". "for x in range(1,101):print"fizz"[x%3*4:]+"buzz"[x%5*4:]or x". Nice list for a newbie.
Max Burstein - 3 months, 3 weeks ago
You're definitely right. I've updated my post to reflect this.
buck learn - 3 months, 3 weeks ago
I didn't exactly understand [x%3*4::] and [x%5*4::] part in the FizzBuzz. Can you explain it please?
Raphael Saunier - 3 months, 3 weeks ago
He's taking the result of the modulus operation and multiplying it by 4 (i.e. the length of "fizz" and "buzz") to then slice each string. When the result of x%3 is 0, the string is left intact, but when it is greater than 0, you're left with an empty string.
Beni Paskin-Cherniavsky - 3 months, 3 weeks ago
Code golf aside, this would be waaay more readable with if-else expressions: print "Fizz" if x % 3 == 0 else "Buzz" if x % 5 == 0 else x
Scott - 3 months, 2 weeks ago
Your code does not produce the intended outcome (i.e., "FizzBuzz") for values that are multiples of 5 AND multiples of 3 (e.g., 15, 30, 45, 60, 75, 90). The logic needs to test every value for both criteria, which the 'golf code' does.
Anonymous - 3 months, 3 weeks ago
Please tell me the name of the text editor and the font. Thanks.
Sad person - 3 months, 3 weeks ago
You make me sad by promoting use of Python 2. In Python 3 True = False is impossible any more because bools are keywords. Also prints. If you've just put parentheses around print arguments, examples would work in Python 3 too.
raxit - 3 months, 3 weeks ago
last one is evil! how can i roll back :) a=True False=True #rest of the stuff goes here True=a
jpihl - 3 months, 3 weeks ago
True = False print True >> False %Do stuff True = 1 == 1 print True >> True
matt - 3 months, 3 weeks ago
To combine lists into key:value pairs: dict(zip(list1, list2))
Mateus Caruccio - 3 months, 3 weeks ago
Dict as named parameters: def add(a, b): return a+b parms={'a':1, 'b'=2} print add(**parms) 3
∆ - 3 months, 3 weeks ago
Typo in list subsets: the slice of last three is [-3:], not [3:0]
Max Burstein - 3 months, 3 weeks ago
Good point about negative indexing. I forgot to include anything on that. x[3:] will give you the last 3 in this case though. I've updated my post to use negative indexing since my example really only worked for a size 6 list.
Paddy3118 - 3 months, 3 weeks ago
I would suggest the beginner work out what is happening before using some of the above. Some should remain fun curiosities to test your skill in understanding how they work, but not to use in production code (e.g. False = True ...)
Vojislav Stojkovic - 3 months, 3 weeks ago
Nice list. I only wish you warned the readers that using the "get" method to get an item from the dictionary is not 100% equivalent to using try/except. 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.
peter - 3 months, 3 weeks ago
Since this is aimed at beginners please explain that some of your examples are specific to a certain python version.
beginner - 3 months, 3 weeks ago
Good point Peter, if any of these examples doesn't work in all python version than its worth including versions.
Jordan - 3 months, 3 weeks ago
Reverse a list: mylist[::-1]
tappi - 3 months, 3 weeks ago
mylist[::-1] doesn't reverse in-place. Using the reverse method of lists is more pythonic if you want to do that. In non in-place reverses i would the global reversed() function which returns a reversed iterator of the sequence given as a parameter.
Java programmer - 3 months, 3 weeks ago
This is a very good list for anyone who is learning python, thanks for sharing.
me - 3 months, 3 weeks ago
the backtick operator (`) has been deprecated long since and got dropped completely in python 3; i'd seriously advise against using it, let alone teaching it to beginners.
harh - 3 months, 3 weeks ago
really cool shortcuts. love them.
ysangkok - 3 months, 3 weeks ago
Many if these don't work for Python 3 though! I consider the behaviour improved, for example, it is no longer possible to do "False = True". Why did you even put this in the article? It would never be done, and it doesn't matter much if it's a keyword or not.
Parker - 3 months, 3 weeks ago
Here is my favorite: >>> it=iter("12345678901234567890 ") >>> for a,b,c in zip(it,it,it): print a,b,c ... 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
Figs - 3 months, 1 week ago
Shouldn't it print 111 222 333 444 555 666?
B-anon - 3 months, 3 weeks ago
What's the best way to replace part of a string? "1234:RealName:25points" --> "1234:AnonymizedName:25points"
Max Burstein - 3 months, 2 weeks ago
You can do: "1234:RealName:25points".replace("Real", "Anonymized")
Kenneth Love - 3 months, 3 weeks ago
Small nit, // isn't floor division, it's integer division. You get "2" back from "5//2" or "5.0//2" because it drops the non-integer portion of the answer.
Beni Paskin-Cherniavsky - 3 months, 3 weeks ago
"floor division" is the official name of the operator, and it's more descriptive because -5 // 2 == -3. Also when you say "integer division" it might be understood as "whatever happens when you divide integers", which returns a float in Python 3 (or 2 with from __future__ import division).
Hyuristyle - 3 months, 3 weeks ago
Hey, good tricks! You could also add this little trick: x = [1,2,3,4,5,6] #Reverse List print x[::-1] >>> [6,5,4,3,2,1]
Drew - 3 months, 3 weeks ago
The [0]*3 is nice, but you have to be careful with it. You can hit a big snag with references For instance: a = [[]]*3 # [[], [], []] a[0].append(0) # [[0], [0], [0]]
Arnab - 3 months, 2 weeks ago
Pretty neat tricks there!! Enjoyed it.
beltorak - 3 months, 2 weeks ago
neat! I think the "if between" shortcut should be illustrated with an array though >>> numbers = range(10) >>> numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for n in numbers: ... if 3 <= n <= 7: ... print n ... 3 4 5 6 7 >>> for n in numbers: ... if not 3 <= n <= 7: ... print n ... 0 1 2 8 9
romppanen - 3 months, 2 weeks ago
Even simpler way to check if an item is in a dictionary: data = {...} is_admin = 'admin' in data
Clive Darke - 3 months, 2 weeks ago
In python <b>2</b> True and False are basically just global variables. In Python 3 they are keywords.
About Me
My name is Max Burstein and I am currently a senior at the University of Central Florida majoring in Information Technology. I enjoy developing large, scalable web applications and I seek to change the world.