Python Notes

regex pattern for any number


Advice from here.

remove comments

for line in f:
    line = line.split('#')[0].strip() # remove comments
    if line:


xor = lambda x, y: True if (x or y) and not (x and y) else False

divide a list

def divide_list(li, n): 
    """ Yield successive n lists of even size.
    start = 0 
    for i in xrange(n):
        stop = start + len(li[i::n])
        yield li[start:stop]
        start = stop

def chunk_list(li, n): 
    """ Yield successive n-sized chunks from l.
    for i in xrange(0, len(li), n): 
        yield li[i:i+n]


>>> a = range(10)
>>> list( divide_list(a, 3) )
[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list( chunk_list(a, 3) )
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

Advice taken from here.

See also:

group = lambda t, n: zip(*[t[i::n] for i in range(n)])
Advice taken from here.

set-difference between two lists

diff_list = [item for item in list1 if not item in list2]
Advice taken from here.
def check_for_missing(haves, wants):
    return [item for item in wants if not item in haves]

emulate switch with a dict

def f(x):
    return {
        'a': 1,
        'b': 2,
        }.get(x, 9)  
Advice taken from here.


timestamp ='%Y-%m-%d_%a_%H:%M:%S')
>>> time.strftime('%Y-%m-%d %H:%M:%S')
'2011-06-08 13:29:49'
>>> time.strftime('%Y-%m-%d-%Hh%M')

dict extract

def extract(d, keys):
    return dict((k, d[k]) for k in keys if k in d)

Sorting Coupled Lists

Often one has several lists where the information stored in the i-th entry of each list is related, and one wants to sort all the lists together according to the entries in one of them. The following sorts two coupled lists according to the first.
zipped = zip(list1, list2)
list1, lists2 = map(list, zip(*zipped))

It can be generalized to several lists by

zipped = zip(*list_of_lists)
list_of_lists = map(list, zip(*zipped))

Default Values for Mutable Parameters

This advice was taken from here.

This is a common mistake that beginners often make. Even more advanced programmers make this mistake if they don't understand Python names.

def bad_append(new_item, a_list=[]):
    return a_list

The problem here is that the default value of a_list, an empty list, is evaluated at function definition time. So every time you call the function with the default parameter, you get the same instance of the list. Try it several times:

>>> print bad_append('one')

>>> print bad_append('two')
['one', 'two']

Lists are a mutable objects; you can change their contents. The correct way to get a default list (or dictionary, or set) is to create it at run time instead, inside the function:

def good_append(new_item, a_list=None):
    if a_list is None:
        a_list = []
    return a_list

For cases where it isn't natural to represent the default case by None, I like to make a default object as a place holder for default parameters.

_default = object()
def f(mut_param=_default):
    if mut_param is _default:
        mut_param = ['some', 'default', 'mutable']


Use enumerate when you want to do a for loop over an iterable with an index. So when you would do
i = 0
for e in elements:
    print i, e
    i += 1
do this instead
for i, e in enumerate(elements):
    print i, e

Path of This File

import os
path_of_this_file = os.path.abspath( __file__ )
dir_of_this_file = os.path.dirname(os.path.abspath( __file__ ))
Old stupid way:
path_of_this_file = os.path.realpath(os.path.dirname(sys.argv[0]))

Console Input

>>> uin = raw_input('my prompt:').strip()
my prompt:   hello world, 1234
>>> uin
'hello world, 1234'

Console Output

import subprocess
p = subprocess.check_output('ls -l -a', stderr=subprocess.STDOUT, shell=True)
print p

Get IP address

s = subprocess.check_output("/sbin/ifconfig | grep -w inet | grep -v | awk '{print $2}' | cut -d ':' -f 2", shell=True).strip() 

-- RyanReece - 17 Oct 2008

Edit | Attach | Watch | Print version | History: r23 < r22 < r21 < r20 < r19 | Backlinks | Raw View | WYSIWYG | More topic actions
Topic revision: r23 - 2013-09-17 - RyanReece
    • Cern Search Icon Cern Search
    • TWiki Search Icon TWiki Search
    • Google Search Icon Google Search

    Sandbox All webs login

This site is powered by the TWiki collaboration platform Powered by PerlCopyright & 2008-2022 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
or Ideas, requests, problems regarding TWiki? use Discourse or Send feedback