5 Minute python

[EDIT] I wrote this quite a long time ago and there are plenty of better introductions to python [/EDIT]

I’ve recently been learning python. Here I’ve documented some of the basic things I wish I knew at the very beginning.

This is just enough to get started but doesn’t include some of the really interesting stuff that you’ll be able to do once you get going.

Getting information out of python

Run the python interpreter on the commandline and get information about a command or module

dir(python_command)
help(python_command)

Lists (Arrays / Vectors)

The basic array type is called list and can grow like a Vector in java.

Creating empty lists

#  content of my cupboard
cupboard_content = list()
cupboard_content = []

A prepopulated list

cupboard_content = ['pasta', 'rice', marmite', 'jam']
print 'items in cupboard:', len(cupboard_content)
print 'first item in cupboard', cupboard_content[0]

Splicing lists

You can retrieve a subset of a list by splicing

# First four elements
print cupboard_content[:4]
# Last four elements
print cupboard_content[:-4]
# For elements, starting at 2
print cupboard_content[2:4]

Tuples

These have an unfamiliar name, but are just immutable lists.

Create a list from a tuple

cupboard_content = list(shopping_bag_content)

Dictionaries (Hashtables / Associative arrays)

Create an empty dict

favourite_fruits = {}
favourite_fruits = dict()

Creating populated dicts

favourite_fruits = { 1: 'Apples',  2: 'Pears', 3: 'Bananas' }

Place and retrieving items

passwords['bob'] = 'secret'
print passwords['bob']

Looping

Generally for loops work like for-each loops in other languages:

# Loop through dict or list
for value in shopping_list:
    print value

# Loop through dictionary
for key, value in dictionary.items():
    print key, value

Traditional for loops

These don’t exist, but you can use ranges or enumerations to get an equivilent (these both generate lists).

Note that you need a colon ":" after any loops (for, while)

for i, value in enumerate(list):
    print i, value
for i in range(0, 10):
    print i

Faking Enums

Python doesn’t have enums, but you can get the same result using a range to set some constants

(BOB, JIM) = range(0, 2)

This will set them to be 0 and 1, range’s parameters are: range(first_item, number_of_items)

Types

Python uses duck typing , in practice this means you don’t have to worry about types a lot of the time, having said that here are some things to bear in mind.

Append to a string

If you want to use the ‘+’ operator to add a non-string to a string then cast it:

print 'Special variable:' + str(variable)

Unlike java when you use a float in an operation the variables won’t be automatically promoted, so when you divide do 5 /2 it will not equal 2.5, you have to divide by 2.0

Packing / Unpacking

Sometimes it’s useful to be able to convert between lists and seperate values, if you have a function like this

def goto_location(name, x, y, z):
    print x, y, z
#  Which you would call like this
goto_location('London', 1, 2, 3)

You might want to be able to pass in a single value as a list and unpack it automatically – like this

def goto_location(name, (x, y, z)):
     print x, y, z
location = 1, 2, 3
goto_location('London', location)