Do I really need to tell you about numbers?
Plain integers and long integers are unified in Python. You don’t need to worry about overflow as it will convert to a long automatically.
import sys
a = sys.maxint
print a
b = a*2
print b
Integer literals are interpreted as plain integers unless they don’t fit in which case they are automatically converted to longs. You can force a literal to be a long by using ‘l’ or ‘L’ as a suffix.
a = 100000000000000000000000000000000000
print a
b = 10
print b
b = 10L
print b
Floats are implemented as a double in the underlying C. You can see the underlying precision using sys.float_info
import sys
print sys.float_info
Integer division returns the floor. If you want to avoid that you can explicitly convert to a float. Converting after the division is too late.
a = 7
b = 2
print a / b
print float(a) / b
print float(a / b)
Integer division no longer returns the floor. You can recreate this behavior in Python 2.6 by importing from the __future__ module.
from __future__ import division
a = 7
b = 2
print a / b
Real and imaginary parts are both stored as floats. Imaginary literals can be created using a ‘j’ or ‘J’ suffix or with the complex() function.
a = 1 + 1j
print a.conjugate()
print complex(2, 5)
print a**2
print a.real
print a.imag
The math module only supports types which can be converted to floats. For math functions which work with complex numbers use the cmath module.
import cmath
a = 1 + 1j
print cmath.log(a)
print cmath.sqrt(a)
Strings are a sequence type to hold character data. String literals can be enclosed in ‘ or ” characters. The backslash character is an escape character.
a = 'blip' # The string blip
b = "blip" # The string blah
Strings can also be marked as raw strings with a r/R in which case the escape character is not needed.
a = '\n' # newline character
print a
b = r'\n' # the string \n
print b
We’ve seens triple quoted strings used as comments. They define string literals which can span more than one line and include the newline characters.
a = """
This string is on multiple lines.
It can be very long if you wish.
"""
Unlike C, Strings are immutable meaning you cannot change them once they are created.
a = 'My test string'
print a[0]
a[0] = 'b' # This will generate an error.
Python uses the same string formatting as printf in C.
a = 10
b = 37.0
print '%i %i' % (a, b)
print '%f %f' % (a, b)
print '%s %s' % (a, b)
You can also used named mappings while formatting strings.
print '%(last)s, %(first)s' % {'first': 'Mark', 'last': 'Lavin'}
More on mappings coming up.
Python 2.6 includes a back-port of new style string formatting as defined by PEP 3101.
# positional arguments
'{0} {1}'.format('Hello', 'World')
# named arguments
'{first} {second}'.format(second='World', first='Hello')
Stings can be combined with the + operator or by using string formatting. Note that the + operator will not change type.
a = 'test'
b = 'string'
c = 10
print a + b
print '%s %s' % (a, b)
print a + c # This will produce an error
print '%s %s' % (a, c)
There are a number of handy string methods built in. Remeber because strings are immutable they return a new string rather than modifying the calling string.
a = 'my test string'
print a.upper()
print a
'test'.capitalize() # returns 'Test'
'test'.endswith('a') # returns False
'test'.find('e') # returns 1 (would return -1 if not found)
'test'.lower() # returns 'test'
'test'.replace('t', 'b') # returns 'besb'
'a b c'.split() # returns ['a', 'b', 'c']
'test'.startswith('i') # returns False
'test string'.title() # returns 'Test String'
'test'.upper() # returns 'TEST'
Check out the full list here: http://docs.python.org/library/stdtypes.html#string-methods
List define a zero-indexed squence of objects.
a = [1, 2, 3]
Items in a list do not need to be the same type. Lists can also be nested.
a = [1, 'a', [2, 'b']]
Accessing items in a list is done with a bracket syntax. You can access one or more index at a time. You can also use negative indexes.
a = [1, 2, 3]
print a[0]
print a[0:1]
print a[-1]
[1, 2, 3].append(4) # Inserts value at the end of the list
[1, 2, 3].extend([4, 5]) # Appends iterable to the end of the list
[1, 2, 3].pop() # Returns first item and removes from the list
[1, 2, 3].count(1) # Returns the number of values which match
[1, 2, 3].index(2) # Returns the first index where value is found
[1, 2, 3].insert(1, 4) # Inserts 4 to position 1
[1, 2, 3].reverse() # Reverses the order of items
Check out the full list here: http://docs.python.org/library/stdtypes.html#mutable-sequence-types
It’s easy to use Python lists as a stack (last-in, first-out).
a = [1, 2, 3]
a.append(4)
print a
print a.pop()
print a
print a.pop()
print a
Tuples are similar to lists but with one large difference. Tuples are immutable meaning you cannot change their values once they are set. Tuples use a parentheses rather than a bracket.
a = (1, 2, 3)
Parentheses around a tuple are optional. This allows for handy things like swapping values and unpacking tuples or lists. But if you type
a = 1, # a is a tuple (1,)
It’s possible to unpack a list or tuple:
a, b, c = [1, 2, 3]
print a
print b
print c
Using a similar syntax you can easily swap to variables:
a = 1
b = 2
a, b = b, a
print a
print b
Dictionaries are key-value mappings. In other contexts or languages they are called associative arrays or maps. They are defined by
a = {'key': 'value'}
a['key']
a['new-key'] = 'new-value'
You check if a key is in a dictionary using in or use get to return a default value if the key does not exist. Trying to access a key which does not exist raise a KeyError
if 'key' in a:
print a['key']
print a.get('key') # returns None if not found
print a.get('key', 1) # returns 1 if not found
You can access all of the keys in a dictionary with the keys function. You can access a list of all values using the values function. You can also iterate over all the key, value pairs using iteritems.
a = {'1': 'a', '2': 'b'}
print a.keys()
print a.values()
for k,v in a.iteritems():
print 'Key %s' % k
print 'Value %s' % v
Sets in Python are much like sets in mathematics. They are an un-ordered collection of objects without duplicates. This allows for fast membership detection as well as familiar set operations.
a = set([1, 2, 3])
b = set([2, 4, 6])
a | b # union
a & b # intersection
a - b # difference
a ^ b # symmetric difference
Comparison operators can be used to check for subsets.
a = set([1, 2, 3])
b = set([1 ,2, 3, 6])
a <= b # Is subset?
a < b # Is strict (non-equal) subset
a >= b # Is superset?
a > b # Is strict (non-equal) superset
While in Python 2.X you must use the set() function to create sets, Python 3 allows for set literals using a brace syntax.
a = {1, 2, 3}
Note that {} is still an dictionary.
Lists and tuples can be unpacked to fill in positional arguments for a function call using *.
def add(x, y):
return x + y
data = (1, 2)
print add(*data)
Dictionaries can be used to fill arguments using **.
def subtract(x, y):
return x - y
data = {'y': 1, 'x': 3}
print subtract(**data) # same as subtract(y=1, x=3)
The built-in bool function is used to convert other types to either True or False. For the most part everything in Python is True except for various empty values.
# False values
0, 0.0 # Zero
'', "" # Empty strings
[], () # Empty lists and tuples
{}, None # Empty dictionaries and None
Creating your own classes!