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 - 1 year, 7 months ago

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

    reply

  • trout - 1 year, 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.

    reply

  • Amir Rachum - 1 year, 7 months ago

    I've written a blog post about this exact issue! http://blog.amir.rachum.com/post/30176371115/you-cant-handle-the-truth

    reply

  • allo - 1 year, 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"

    reply

  • allo - 1 year, 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.

    reply

  • Halex - 1 year, 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.

    reply

  • Max Burstein - 1 year, 7 months ago

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

    reply

  • buck learn - 1 year, 7 months ago

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

    reply

  • Raphael Saunier - 1 year, 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.

    reply

  • Beni Paskin-Cherniavsky - 1 year, 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

    reply

  • Scott - 1 year, 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.

    reply

  • Anonymous - 1 year, 7 months ago

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

    reply

  • Sad person - 1 year, 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.

    reply

  • raxit - 1 year, 7 months ago

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

    reply

  • jpihl - 1 year, 7 months ago

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

    reply

  • matt - 1 year, 7 months ago

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

    reply

  • Mateus Caruccio - 1 year, 7 months ago

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

    reply

  • ∆ - 1 year, 7 months ago

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

    reply

  • Max Burstein - 1 year, 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.

    reply

  • Paddy3118 - 1 year, 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 ...)

    reply

  • Vojislav Stojkovic - 1 year, 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.

    reply

  • peter - 1 year, 7 months ago

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

    reply

  • beginner - 1 year, 7 months ago

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

    reply

  • Jordan - 1 year, 7 months ago

    Reverse a list: mylist[::-1]

    reply

  • tappi - 1 year, 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.

    reply

  • Java programmer - 1 year, 7 months ago

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

    reply

  • me - 1 year, 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.

    reply

  • harh - 1 year, 7 months ago

    really cool shortcuts. love them.

    reply

  • ysangkok - 1 year, 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.

    reply

  • Parker - 1 year, 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

    reply

  • Figs - 1 year, 7 months ago

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

    reply

  • B-anon - 1 year, 7 months ago

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

    reply

  • Max Burstein - 1 year, 7 months ago

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

    reply

  • Kenneth Love - 1 year, 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.

    reply

  • Beni Paskin-Cherniavsky - 1 year, 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).

    reply

  • Hyuristyle - 1 year, 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]

    reply

  • Drew - 1 year, 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]]

    reply

  • Arnab - 1 year, 7 months ago

    Pretty neat tricks there!! Enjoyed it.

    reply

  • beltorak - 1 year, 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: ... <= 7: ... print n ... 3 4 5 6 7 >>> for n in numbers: ... if not 3 <= n <= 7: ... print n ... 0 1 2 8 9

    reply

  • romppanen - 1 year, 7 months ago

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

    reply

  • Clive Darke - 1 year, 7 months ago

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

    reply

  • Anonymous - 8 months, 3 weeks ago

    how to avoid float division like that?

    reply

  • Max Burstein - 8 months, 3 weeks 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)
    

    reply