Skip to content

Instantly share code, notes, and snippets.

@thom801
Last active June 7, 2017 23:08
Show Gist options
  • Save thom801/5207725 to your computer and use it in GitHub Desktop.
Save thom801/5207725 to your computer and use it in GitHub Desktop.
Python Language Elements

Python Language Elements

Classes

Below is a breakdown of the following Class definition and a little about what each part of it does.

class ClassName(object):
  """docstring for ClassName"""

	attribute = 10

	def __init__(self, arg):
		super(ClassName, self).__init__()
		self.arg = arg

	def myClassName(self):
		return self.name
class 

Defines a class. Accepts one parameter that defines the Class it will inherit from. Classes support full object oriented inheritance, methods, attributes and constructors. The only property a class must have is a name. Usually indicated using upper case names, ie: MyClassName.

def

Function definition keyword. When used within a class this keyword is used as a method definition keyword and can be used to override existing methods such as init which is explained next.

__init__()

The Class constructor. init is the first method called when an instance of a Class is instantiated. It may be overriden as illustrated above in the class definition.

super(ClassType, self)

super is a proxy object that delegates method calls to a parent or sibling class of the ClassType it is passed.

self 

self is a variable representing the instance of the object. Python does not pass this to each method automatically so you need to do so explicitly. However if you pass another parameter to that method, when the method is called, you only pass the second parameter and ignore self.

Lists

list

A List is a MUTABLE sequence type. It CAN be modified after definition.

definition

myList = [1,2,3]

iteration

for x in myList: print x # 1, 2, 3

tests

1 in myList # True
len(myList) # 3

Tuples

tuple

Tuple is in IMMUTABLE sequence type. It CANNOT be modified after definition.

definition

myTuple = (1,2,3) # (1,2,3)
myTuple = tuple('abc') # ('a', 'b', 'c')

iteration

for x in myTuple: print x # 1, 2, 3

tests

1 in myTuple # True

Sets

set

Sets are UNORDERED, MUTABLE lists of UNIQUE items. ImmutableSet is similar but IMMUTABLE.

definition

mySet = set([1,2,3])

iteration

for x in mySet: print x # 1, 2, 3

tests

1 in mySet # True

Dictionaries

dict

Dictionaries are versatile data sets consisting of key value pairs.

Definition with standard data types.

yields {'myInteger': 100, 'myString': 'Hello World'}
myDict = { 'myString': "Hello World!", 'myInteger': 100 } 

Definition with existing variables

yields {'mySet': set([1, 2, 3]), 'myList': [1, 2, 3], 'myTuple': (0, 1, 2)}
myDict = { 
  'myList': myList, 
  'myTuple': myTuple, 
  'mySet': mySet 
} 

Accessing values

myDict['myString'] # "Hello World!"
myDict['myList'] # [1,2,3]
# inserting values
myDict['newString'] = 'All your base are belong to us!'
myDict['newInteger'] = 100

Range

range()

function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers.

Stop argument

range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Start and stop arguments

range(5,10) # [5, 6, 7, 8, 9]

Start, stop and step arguments

range(5,100,5) # [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

xRange

xrange()

similar to range, but returns an xrange object instead of a list. Yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange is negligable except for when a very large range is used and memory conservation is important.

Definition

myRange = xrange(0, 1000000000) # xrange(1000000000)

Access values similar to a list

myRange[10000] # 10000

Enumerate

enumerate()

Returns an enumerate object. Accepts a sequence that must support iteration.

seasons = ["Spring", "Summer", "Fall", "Winter"]
list(enumerate(seasons)) # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start=1)) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

aList = ['a', 'b', 'c']
for index, item in enumerate(aList): print index, item 

# 0 a
# 1 b
# 2 c

Zip

zip

Combines two lists and returns a list of tuples containing values of each list in the order they were passed.

x, y = [1,2,3], ['a','b','c']
zipped = zip(x,y) # [(1, 'a'), (2, 'b'), (3, 'c')]
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
	print 'What is your {0}?  It is {1}.'.format(q, a)

# What is your name?  It is lancelot.
# What is your quest?  It is the holy grail.
# What is your favorite color?  It is blue.

Map

map

performs an operation against each indice of a list.

a = [1,2,3,4,5]
b = [5,4,3,2,1]

def isGreaterThan(x, y):
	isGreater = x > y
	print '{0} is greater than {1}: {2}'.format(x, y, isGreater)

map(isGreaterThan, a, b)

# 1 is greater than 5: False
# 2 is greater than 4: False
# 3 is greater than 3: False
# 4 is greater than 2: True
# 5 is greater than 1: True

Lambda

lambda x: x * 2

Lambda forms, or lambda expressions are a shorthand way to create anonymous functions on the fly.

Lambda expression to add 2 to a number.

plusTwo = lambda x: x + 2
plusTwo(2) # 4

Lambda expression to return the exponential value of two numbers

getExp = lambda x, y: x**y
getExp(5,5) # 3125

Lambda expression to return a list of numbers in a range based on an incremental value

incrementInRange = lambda num,min,max: [ x for x in range(min,max) if x % num == 0 ]
incrementInRange(3,0,30) # [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
incrementInRange(2,40,60) # [40, 42, 44, 46, 48, 50, 52, 54, 56, 58]

List Comprehensions

[ x for x in range(10) ]

List comprehensions provide a concise and powerful way to create lists based on mathematical and logical operations. This is commonly used to apply a calculation against each member of an iterable data set.

Add name to list for name in ourNames if name is in commonNames

commonNames = ['Tom', 'Dick', 'Harry']
ourNames = ['Tom', 'Bob', 'Ron', 'Peter', 'Harry']
[ name for name in ourNames if name in commonNames ] 
# ['Tom', 'Harry']

Return a list of x in a range from 0 to 10

[ x for x in range(10) ] 
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Return a list of x * 5 in a range from 1 to 10

[ x * 5 for x in range(1,10) ] 
# [5, 10, 15, 20, 25, 30, 35, 40, 45]

Return a list of tuples (x, y) for x in a range from 0 to 4 and y in a range from 4 to 0 if x > y

[ (x, y) for x in range(4) for y in range(4, 0, -1) if x > y ] 
# [(2, 1), (3, 2), (3, 1)]

Return a list of tuples (x, y) for x in the list [1,2,3] for y in the list [3,1,4] if x != y

[ (x, y) for x in [1,2,3] for y in [3,1,4] if x != y ] 
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Functions

def functionName(parameterName):

Functions are blocks of code that can be executed and passed parameters.

Python passes values by reference. Therefore if you assign a new value the passed in variable it WILL NOT affect the original variable. However, if you perform an operation on that referenced variable it WILL affect the original variable.

def try_to_change_list_contents(the_list):
  print 'got', the_list # got ['one', 'two', 'three']
  the_list.append('four')
  print 'changed to', the_list # changed to ['one', 'two', 'three', 'four']

outer_list = ['one', 'two', 'three']

print 'before: ', outer_list # before: ['one', 'two', 'three']
try_to_change_list_contents(outer_list)
print 'after: ', outer_list # after: ['one', 'two', 'three', 'four']

Since the parameter passed in is a reference to outer_list, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.

def try_to_change_list_reference(the_list):
  print 'got', the_list # got ['we', 'like', 'proper', 'English']							
  the_list = ['and', 'we', 'can', 'not', 'lie'] 
  print 'set to', the_list # set to ['and', 'we', 'can', 'not', 'lie']

outer_list = ['we', 'like', 'proper', 'English']

print 'before, outer_list =', outer_list # before: ['we', 'like', 'proper', 'English']
try_to_change_list_reference(outer_list)
print 'after, outer_list =', outer_list # after: ['we', 'like', 'proper', 'English']

Since the the_list parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list was a copy of the outer_list reference, and we had the_list point to a new list, but there was no way to change where outer_list pointed.

def try_to_change_string_reference(the_string):
  print 'got', the_string # got It was many and many a year ago
  the_string = 'In a kingdom by the sea'
  print 'set to', the_string # It was many and many a year ago

outer_string = 'It was many and many a year ago'

print 'before: ', outer_string # before: It was many and many a year ago
try_to_change_string_reference(outer_string) 
print 'after: ', outer_string # after: It was many and many a year ago

Again, since the the_string parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string was a copy of the outer_string reference, and we had the_string point to a new list, but there was no way to change where outer_string pointed.

Regular Expressions

re.search(r'\wegular\s\wxpressions\W', 'Python Regular Expressions!')

Regular expressions are a powerful language for matching text patterns.

Import the "re" (regular expressions) module.

import re

Raw string declaration. It's recommended to always use raw strings when writing regex patterns.

r''

Matches ordinary characters just match themselves exactly

' a, X, 9, < '

Meta characters that will not match exactly

' ^ $ + ? { [ ] \ | ( ) '

Matches any single character other than a newline character.

' . '

Matches a word character: a letter or digit or underbar [a-zA-Z0-9_].

' \w '

Matches any NON word character.

' \W '

Boundary between word and non word.

' \b '

Match a single whitespace character -- space, newline, return, tab, form [\n\r\t\f].

' \s '

Match tab, newline, return.

' \t, \n, \r '

Decimal digit [0-9]

' \d '

Match the start or end of the string.

' ^ = start, $ = end '

Inhibit the "specialness" of a character. \ and . are examples of where this would be needed. You can place a slash in front of any character to make sure it is treated as a normal character.

' \ '

Matches consecutive occurences of the character to its left.

' + '

0 or more occurences of the pattern on its left.

' * '

Match 0 or 1 occurances of the pattern to its left.

' ? '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment