Python

Allowing multiple parameters in a function

You can allow a function to take many parameters by adding the * before the argument>

def printMany(*param): print param
Works like this

printMany('this','is','a','string')
('this', 'is', 'a', 'string')

Tags: 

Using zip()

Takes two lists as parameters and returns a list of tuples where the i-th tuple contains the i-th items from each sequence. This is best explained with an example.

>>> x = ['a','b','c']
>>> y = ['d','e','f']
>>> zipped = zip(x,y)
>>> zipped
[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>>

Tags: 

Abstraction

Abstraction lets the programmer group a bunch of statements together into functions.

text = 'This is a string'
result = 0
text = text.replace(' ','')#get rid of spaces
for char in text:# now count the characters
result += 1
>>>result
13

Now instead of typing all this code out again the next time we need to count the number of characters in a string we could put it in a function like this.

#countChars.py

Tags: 

Extend

Concatenate two lists

>>> list1 = [1,2,3,4,5,6,7,8]
>>> list2 = [9,10,11]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11]
>>> list2
[9, 10, 11]
>>>

Tags: 

Filter

Filter takes a list and applies a function to that list.
filter(function, iterable) Construct a list from those elements of iterable for which function returns true.

>>> list
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> filter(lambda n: n%3 == 0, list)
[0, 6, 12, 18]
>>>

Tags: 

Map

Maps one sequence into another. map(function, iterable, ...) Apply function to every item of iterable and return a list of the results.

>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> map(lambda n: n *2, lst)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
>>>

Tags: 

List Comprehension

A way of making lists from lists

>>> [x for x in range(20) if x%2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>

Tags: 

Dealing with sequences

Sequences are numbered from 0 upward so you can access them like this

>>> myString = "This is a string"
>>> string[0]
'T'
>>> string[0:4]
'This'
>>>

Tags: 

Add Module To Python Program

To add a module to your program, add this to the top of your program

import sys
sys.path.append('c:/my_python_modules')

Tags: 

Find Out What A Module Contains

To find out what the built in module math contains first import it using
import math
Then perform a dir() on it
dir(math)
This returns a list of all the functions available in that module

Tags: 

Pages

Subscribe to RSS - Python