Favorite Python One-liners

May 21, 2015

So, these are not really one-liners as much as they are useful snippets of code I seem to always use or always look for. Feel free to add your own in the comments.

Decode base64 File

import base64, sys;
base64.decode(open(sys.argv[1], "rb"), open(sys.argv[2], "wb"))

Sum Numbers

print sum(range(1,100))

Min and Max

print min([1, 5, 2, -1, 0])
print max([1, 5, 2, -1, 0])

Cache Function Results for Faster Performance (Decorators)

You've got some extra work on your hands if you want to use this before Python 3.2.3.

import functools
def fib(n):
    return 1 if n < 2 else fib(n-1) + fib(n-2)
print fib(5)

Swap Values

x = 1
y = 2
x, y = y, x
print x
print y

Interate Over 2 Lists in 1 Loop

list1 = ["apples", "oranges"]
list2 = ["bag", "bucket"]
for a, b in zip(list1, list2):
    print a + " are in a " + b

Hackery with FizzBuzz

for x in range(1,101):
    print "Fizz" [x%3*4:] + "Buzz" [x%5*4:] or x

Write to File

with open('foo.txt', 'w') as f:
    f.write('hello world')

Read File Lines Into Array Stripped

lines = [line.strip() for line in open('foo.txt')]

Evaluate a String as as Python

expression = "[1, 2, 3, 4, 5]" 
list = eval(expression)
print list

Set a Breakpoint in Your Script

Just call pdb.set_trace() anywhere in your script to set a breakpoint.

import pdb

Profile Your Script

import profile

Start A Web Server

Start a web service on port 8000 that uses the current directory as its document root.
python -m SimpleHTTPServer

Related Posts