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


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:

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}
    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


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})


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"
    print "World"

>>> Hello

If you've got any other cool tips/tricks leave them in the comments below. Thanks for reading!

Tags: Python


  • Juho Vepsäläinen - 2 years, 7 months ago

    A couple to add: sets, yield, decorators, functools. functools in particular contains some powerful functions such as partial. Good list overall.


  • trout - 2 years, 7 months 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 - 2 years, 7 months ago

    I've written a blog post about this exact issue!


  • allo - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months ago

    You're definitely right. I've updated my post to reflect this.


  • buck learn - 2 years, 7 months ago

    I didn't exactly understand [x%3*4::] and [x%5*4::] part in the FizzBuzz. Can you explain it please?


  • Raphael Saunier - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months ago

    Please tell me the name of the text editor and the font. Thanks.


  • Sad person - 2 years, 7 months 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 - 2 years, 7 months ago

    last one is evil! how can i roll back :) a=True False=True #rest of the stuff goes here True=a


  • jpihl - 2 years, 7 months ago

    True = False print True >> False %Do stuff True = 1 == 1 print True >> True


  • matt - 2 years, 7 months ago

    To combine lists into key:value pairs: dict(zip(list1, list2))


  • Mateus Caruccio - 2 years, 7 months ago

    Dict as named parameters: def add(a, b): return a+b parms={'a':1, 'b'=2} print add(**parms) 3


  • ∆ - 2 years, 7 months ago

    Typo in list subsets: the slice of last three is [-3:], not [3:0]


  • Max Burstein - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months ago

    Since this is aimed at beginners please explain that some of your examples are specific to a certain python version.


  • beginner - 2 years, 7 months ago

    Good point Peter, if any of these examples doesn't work in all python version than its worth including versions.


  • Jordan - 2 years, 7 months ago

    Reverse a list: mylist[::-1]


  • tappi - 2 years, 7 months 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 - 2 years, 7 months ago

    This is a very good list for anyone who is learning python, thanks for sharing.


  • me - 2 years, 7 months 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 - 2 years, 7 months ago

    really cool shortcuts. love them.


  • ysangkok - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 6 months ago

    Shouldn't it print 111 222 333 444 555 666?


  • B-anon - 2 years, 7 months ago

    What's the best way to replace part of a string? "1234:RealName:25points" --> "1234:AnonymizedName:25points"


  • Max Burstein - 2 years, 7 months ago

    You can do: "1234:RealName:25points".replace("Real", "Anonymized")


  • Kenneth Love - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months 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 - 2 years, 7 months ago

    Pretty neat tricks there!! Enjoyed it.


  • beltorak - 2 years, 7 months 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 - 2 years, 7 months ago

    Even simpler way to check if an item is in a dictionary: data = {...} is_admin = 'admin' in data


  • Clive Darke - 2 years, 7 months ago

    In python 2 True and False are basically just global variables. In Python 3 they are keywords.


  • Anonymous - 1 year, 8 months ago

    how to avoid float division like that?


  • Max Burstein - 1 year, 8 months ago

    You can round your numbers. If you're doing something with currency you may not need more than 2 decimal places. So you could do something like this:

    round(.3/.1, 2)


  • Nancy Rani - 5 months, 2 weeks ago

    Python Shortcuts for the Python Beginner for Web site Links in Below, <a href="">Python beginner </a> <a href=""> Oracle DBA Training in Chennai </a>


  • Ganesh - 4 months, 4 weeks ago

    Thanks for sharing this Information blog. Recently I have completed Oracle Training Courses in Bangalore at a leading Company. It's really useful for me to make a bright Future career. Visit Us, <a href=""> Oracle Training Institute Bangalore </a>


  • Surya - 4 months, 4 weeks ago

    I have joined the oracle Trained in Training in Bangalore. Oracle Trainer will be teaching in practically Manner. So I can Easily able to understand the any Concept. This is very helpful for the interviews Purpose . I would refer my frnds to joined this institute.....


  • Oracle Training in Chennai - 4 months, 3 weeks ago

    thanks for sharing this informative blog..


  • kana6 - 4 months, 1 week ago

    They are offer the best python training for students.This course is very useful for you career.Thank you for sharing you article.<a href="">python training in Chennai</a>


  • PHP Training in Chennai - 3 months, 1 week ago

    Thanks for Sharing the shortcuts. Its very useful to me.


  • girlsdoporn - 2 months ago

    Hi there, I would like to know What does this line of code means : maxint = (2**(0.size * 8 -2) -1) How did you even know what are the values for maxint?


  • Salesforce Training in Chennai - 2 months ago

    Thanks for the article


  • lakshmi - 2 months ago

    Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard


  • The Best Places for Writing a Dissertation That Ro - 1 month, 3 weeks ago

    I wish more authors of this type of content would take the time you did to research and write so well. I am very impressed with your vision and insight.


  • Arnold Barclay - 1 month, 1 week ago

    These tactics and methods helps for those who are the beginners of these studies.


  • Jaman - 1 month, 1 week ago

    Excellent blog and its very useful for python beginners..


  • Elder abuse lawyer - 1 month, 1 week ago

    I have read the post it is very informative.You have done a great job.I will share the post with my friends.


  • leenadeep - 3 weeks ago

    ya,I agree with your thoughts...


  • xarelto lawsuit - 1 month, 1 week ago

    Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that. Thanks so lot for your convene.


  • green smart living - 1 month, 1 week ago

    Such intelligent work on the subject and ideal way of writing here. I am really impressed! This post is a helpful overview of the particular topic and very actionable. Interesting approach!


  • peppin bright - 1 week, 6 days ago

    Great information are sharing..Thanks for that..


  • lucy - 1 month ago

    nice tips for python beginners as file extensions are .py, .pyc, .pyd, .pyo, .pyw .what it mean for differed as C++ and java. I like python because is easy for learn and understand the function as possible.


  • - 1 month ago

    I am exceptionally happy to see this post. Really I have been looking for such sort of post. A debt of gratitude is in order for giving this post.


  • Buy real YouTube Views via Paypal - 1 month ago

    I discovered this post exceptionally accommodating. I'm seeking after some more educational posts. Much obliged to you for sharing awesome data.


  • Download Hack Tracker - 1 month ago

    This really is an astounding article. What's more, I truly say with my unadulterated heart that this is the most true article that I have ever lived to see till now.


  • learn seo - 4 weeks, 1 day ago

    I am practically satisfied with you're great work.You put truly exceptionally supportive data Great a debt of gratitude is in order for sharing this article post.


  • diabetes destroyer - 2 weeks, 6 days ago

    The data in plain vie w here is simply unbelievable. There is not one thing that I might want to change about this article.


  • pregnancy miracle guide - 2 weeks, 3 days ago

    thanks for the post. Python is getting more popular.


  • - 2 weeks, 2 days ago

    Totally a fantastic site you've got in the accompanying indeed. much appreciated with the uncover and in addition offer my companion.


  • gaming server - 2 weeks, 1 day ago

    Incredible work.Much appreciated, incredible share.I am continually scanning online for articles that can help me.


  • Chicago Motor Coach - 2 weeks ago

    I will remember it, much obliged for sharing the data, looking forward for more posts. Upbeat imperative data I got out of your site.


  • hacker dragon city - 2 weeks ago

    This article has great title with great depiction.I concede with your Blog and I will be back to investigate it more later on so please keep up your work.


  • Orange Beach Beach Rentals - 2 weeks ago

    Simone was Mark’s first love but she dumped him seven years ago. When he thinks he has the opportunity to see her again, and to possibly fuck her, his balls begin to ache in anticipation.


  • NelfonRowl - 1 week, 6 days ago

    cialis information side effects last post [url=]cialis without a doctor's prescription [/url] prostate and cialis <a href="">cialis without a doctor's prescription </a> - buy cialis site%3 cialis from canada cheap categories


  • Puja Kumari - 1 week, 6 days ago

    Thanks for post this helpful post - Please visit for More information about:


  • Puja Kumari - 1 week, 6 days ago

    Thanks for Nice and Informative Post. This article is really contains lot more information about This Topic


  • eskamon - 1 week, 5 days ago

    I was considering utilizing this style for the site I am going to build for my school venture. This was a truly fabulous examination for me.


  • Luggage Online - 1 week, 5 days ago

    I am happy to find this post very useful for me, as it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing.


  • tinnitus miracle - 1 week, 3 days ago

    Thank you for sharing this info with us. Python will be one of the major languages soon I assume.


  • carry-on - 1 week, 2 days ago

    I have bookmarked your blog, the articles are way better than other similar blogs.. thanks for a great blog!


  • project free tv unblocked - 1 week, 2 days ago

    I took in a ton of information from which to take in more things.


  • - 5 days, 17 hours ago

    I will most likely return. Your post is basically stupendous and I can accept you are a specialist on this field.


  • look at this - 5 days, 4 hours ago

    You are so capable! I am likewise keen on this subject. I have invested a great deal of energy in looking this sort of subject.


  • facebook password hacker - 3 days, 18 hours ago

    I will be your dependable peruser. What an awesome post ! it was totally genuine informative.


  • Vera bradley handbag - 3 days, 15 hours ago

    Interesting and amazing how your post is! It Is Useful and helpful for me That I like it very much, and I am looking forward to Hearing from your next..


  • - 2 days, 17 hours ago

    I genuinely welcome your endeavors and I am sitting tight for your next review thanks once again.Wonderful post.


  • treating gut dysbiosis - 20 hours ago

    Good post! Your post is an excellent example of why I keep coming back to read your excellent quality content that is forever updated. Thank you!