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.maxsize
a
9223372036854775807
a * 2
18446744073709551614
Floats are implemented as a double in the underlying C. You can see the underlying precision using sys.float_info
.
import sys
sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
a = 7
b = 2
a / b
3.5
a // b
3
float(a) / b
3.5
Real and imaginary parts are both stored as floats. Imaginary literals can be created using a j
or J
suffix or with the complex
built-in function.
a = 1 + 1j
a.conjugate()
(1-1j)
complex(2, 5)
(2+5j)
a ** 2
2j
a.real
1.0
a.imag
1.0
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
cmath.log(a)
(0.34657359027997264+0.7853981633974483j)
cmath.sqrt(a)
(1.09868411346781+0.45508986056222733j)
Strings are a sequence type to hold character data. String literals can be enclosed in '
or "
characters. The backslash character is an escape character.
'blip' # The string blip
'blip'
"blah" # The string blah
'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
a
'\n'
b = r'\n' # the string \n
b
'\\n'
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'
a[0]
'M'
a[0] = 'b' # This will generate an error.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-82-0522789a4d6d> in <module>() ----> 1 a[0] = 'b' # This will generate an error. TypeError: 'str' object does not support item assignment
Python 3.6 has three methods of string formatting: %
operator, the format
method, and f
strings (new in Python 3.6)
first_name = 'Mark'
last_name = 'Lavin'
'%s %s' % (first_name, last_name)
'Mark Lavin'
'{} {}'.format(first_name, last_name)
'Mark Lavin'
f'{first_name} {last_name}'
'Mark Lavin'
The %
operator uses the same string formatting as printf
in C.
a = 10
b = 37.0
'%i %i' % (a, b)
'10 37'
'%f %f' % (a, b)
'10.000000 37.000000'
'%s %s' % (a, b)
'10 37.0'
You can also used named mappings while formatting strings.
'%(last)s, %(first)s' % {'first': 'Mark', 'last': 'Lavin'}
'Lavin, Mark'
More on mappings coming up.
This method was introduced as part of (PEP 3101)[https://www.python.org/dev/peps/pep-3101/].
# positional arguments
'{0} {1}'.format('Hello', 'World')
'Hello World'
# named arguments
'{first} {second}'.format(second='World', first='Hello')
'Hello World'
This newest format method is new in Python 3.6 as part of (PEP 498)[https://www.python.org/dev/peps/pep-0498/]. This was meant to reduce boilerplate by taking values from the available local namespace.
price = 10
name = 'book'
f'The {name} costs ${price:0.2f}'
'The book costs $10.00'
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
a + b
'teststring'
'%s %s' % (a, b)
'test string'
a + c # This will produce an error
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-95-fefdc3b5f546> in <module>() ----> 1 a + c # This will produce an error TypeError: must be str, not int
'%s %s' % (a, c)
'test 10'
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'
a.upper()
'MY TEST STRING'
a
'my test string'
'test'.capitalize()
'Test'
'test'.endswith('a')
False
'test'.find('e')
1
'test'.lower()
'test'
'test'.replace('t', 'b')
'besb'
'a b c'.split()
['a', 'b', 'c']
'test'.startswith('i')
False
'test string'.title()
'Test String'
Check out the full list here: http://docs.python.org/library/stdtypes.html#string-methods
The str
type has native Unicode support with the default of UTF-8 encoding. They can be included as UTF-8 literals within the source code or by using the \u
and specifying the code point.
'☃' == '\u2603'
True
If you want a raw squence of bytes you can use the b
prefix on a string. The convertion of bytes -> unicode string is done with the decode
method. You can convert a unicode string to bytes using decode
. Both optionally take the character encoding.
heart = b'\xe2\x9d\xa4'
heart.decode()
'❤'
List define a zero-indexed squence of objects.
[1, 2, 3]
[1, 2, 3]
Items in a list do not need to be the same type. Lists can also be nested.
[1, 'a', [2, 'b']]
[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]
a[0]
1
a[0:1]
[1]
a[-1]
3
Check out the full list here: http://docs.python.org/library/stdtypes.html#mutable-sequence-types
[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
3
[1, 2, 3].count(1) # Returns the number of values which match
1
[1, 2, 3].index(2) # Returns the first index where value is found`
1
[1, 2, 3].insert(1, 4) # Inserts 4 to position 1
[1, 2, 3].reverse() # Reverses the order of items
It's easy to use Python lists as a stack (last-in, first-out).
a = [1, 2, 3]
a.append(4)
a
[1, 2, 3, 4]
a.pop()
4
a
[1, 2, 3]
a.pop()
3
a
[1, 2]
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,)
a
(1,)
It's possible to unpack a list or tuple:
a, b, c = [1, 2, 3]
a
1
b
2
c
3
Using a similar syntax you can easily swap to variables:
a = 1
b = 2
a, b = b, a
a
2
b
1
Python 3 allows for more advanced unpacking syntax. This allows for unpacking only part of a list or tuple.
head, *rest, tail = ['a', 'b', 'c', 'd', 'e']
head
'a'
tail
'e'
rest
['b', 'c', 'd']
Dictionaries are key-value mappings. In other contexts or languages they are called associative arrays or maps. They are defined by using a brace syntax:
a = {'key': 'value'}
a['key']
'value'
a['new-key'] = 'new-value'
a
{'key': 'value', '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
:
'key' in a
True
'missing' in a
False
a['missing']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-138-b548a192f37f> in <module>() ----> 1 a['missing'] KeyError: 'missing'
a.get('missing')
a.get('missing', 'default')
'default'
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 items
.
a.keys()
dict_keys(['key', 'new-key'])
a.values()
dict_values(['value', 'new-value'])
for k, v in a.items():
print('Key %s' % k)
print('Value %s' % v)
Key key Value value Key new-key Value new-value
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
{1, 2, 3, 4, 6}
a & b # intersection
{2}
a - b # difference
{1, 3}
a ^ b # symmetric difference
{1, 3, 4, 6}
Comparison operators can be used to check for subsets.
a = set([1, 2, 3])
b = set([1 ,2, 3, 6])
a <= b # Is subset?
True
a < b # Is strict (non-equal) subset
True
a >= b # Is superset?
False
a > b # Is strict (non-equal) superset
False
While in Python 2.X you must use the set()
function to create sets, Python 3 allows for set literals using a brace syntax. Note that {}
is still an dictionary.
a = {1, 2, 3}
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)
add(*data)
3
Dictionaries can be used to fill arguments using **
.
def subtract(x, y):
return x - y
data = {'y': 1, 'x': 3}
subtract(**data) # same as subtract(y=1, x=3)
2
Python has built in logical constants: True
, False
, None
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!