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

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


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

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


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

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


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

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


  • matt - 2 years, 2 months ago

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


  • Mateus Caruccio - 2 years, 2 months ago

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


  • ∆ - 2 years, 2 months ago

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


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

    Reverse a list: mylist[::-1]


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

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


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

    really cool shortcuts. love them.


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

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


  • B-anon - 2 years, 2 months ago

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


  • Max Burstein - 2 years, 2 months ago

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


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

    Pretty neat tricks there!! Enjoyed it.


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

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


  • Clive Darke - 2 years, 2 months ago

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


  • Anonymous - 1 year, 3 months ago

    how to avoid float division like that?


  • Max Burstein - 1 year, 3 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 - 1 month, 1 week 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 - 2 weeks, 6 days 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 - 2 weeks, 6 days 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 - 1 week, 6 days ago

    thanks for sharing this informative blog..


  • kana6 - 3 days, 10 hours 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>