Python: the barebone basics, and a bit more

lists (or arrays?)

a = [1,2,3]

a.insert(0) // insert at the beginning of the array

a.append(4) // append at the end

b = [5,6]

c = a + b // lists can be concatenated

print c[:2] // and sliced (prints [1,2]

print c[2:] // prints [3,4,5,6]

for i in c:

print i   // and iterated…

d = [x * 3 for x in a if x % 2 == 0] // Or mapped to create a new list (d = [6,12])

tuples

They are inmutable lists, useful to package objects:

a = (1,2, ‘hello’)

x,y,z = a // print x = 1, print y = 2, print z = ‘hello’

a = 1, // The () are optional, but if you have only one object, put a comma to indicate tuple

dict

pretty much hash tables:

a = {‘k’:’v’,’k2′:’v2′}

a[‘k’] // v

a.has_key(‘k2′) // True

a = dict(k=’v’, k2=3) // Alternative way to build dict

print a.values() // [‘v’,3]

print a.items() // [(‘k’,’v’),(‘k2’,3)] Note that the results are a list of truples

del a[‘k’] // delete a value

you can also delete values from arrays by indicating the index (a[1])

You can add values to the dictionary using update:

myDict.update(myOtherDic) // Same as Javascript extend. It merges both objects into myDict

Getting the first key:

dict[dict.keys()[0]]

Functions

def f(a, b):
return a + b // Basically functions have a definition (def) and a return

def f(a, b=2): // You can also define variables before you pass them as args

x, y = f(b=5, a=2) // You can have two returns!

return a + b, a – b

def f(*a, **b): // This one is a trip! The first arg, *a, stores all the single args, and **b stores all the pair value args. So:

return a, b

x, y = f(3, ‘hello’, c=4, test=’world’) // a = (3, ‘hello’) and b = {‘c’:4, ‘test’:’world’}

lambda

Sort of like an anonymous function in JavaScript, it is just a convenient way to not have to write a full fledged function for in-between operations.

map(lambda x: x + 2, a) // Where a = [1,4,7] and the result is [3,6,9]

Pretty printing objects in phyton

import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(your_object_here)

Leave a comment

Your email address will not be published. Required fields are marked *