Native Types in Python

  • Numbers
  • Strings
  • Lists
  • Tuples
  • Sets
  • Dictionaries
  • Built-in Constants

Numbers

Do I really need to tell you about numbers?

Integers

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.

In [63]:
import sys

a = sys.maxsize
a
Out[63]:
9223372036854775807
In [64]:
a * 2
Out[64]:
18446744073709551614

Floats

Floats are implemented as a double in the underlying C. You can see the underlying precision using sys.float_info.

In [65]:
import sys

sys.float_info
Out[65]:
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)

Division

In [66]:
a = 7
b = 2
a / b
Out[66]:
3.5
In [67]:
a // b
Out[67]:
3
In [68]:
float(a) /  b
Out[68]:
3.5

Complex Numbers

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.

In [69]:
a = 1 + 1j
a.conjugate()
Out[69]:
(1-1j)
In [70]:
complex(2, 5)
Out[70]:
(2+5j)
In [71]:
a ** 2
Out[71]:
2j
In [72]:
a.real
Out[72]:
1.0
In [73]:
a.imag
Out[73]:
1.0

Complex Math

The math module only supports types which can be converted to floats. For math functions which work with complex numbers use the cmath module.

In [74]:
import cmath

a = 1 + 1j
cmath.log(a)
Out[74]:
(0.34657359027997264+0.7853981633974483j)
In [75]:
cmath.sqrt(a)
Out[75]:
(1.09868411346781+0.45508986056222733j)

Strings

Strings are a sequence type to hold character data. String literals can be enclosed in ' or " characters. The backslash character is an escape character.

In [76]:
'blip' # The string blip
Out[76]:
'blip'
In [77]:
"blah" # The string blah
Out[77]:
'blah'

Raw Strings

Strings can also be marked as raw strings with a r/R in which case the escape character is not needed.

In [78]:
a = '\n' # newline character
a
Out[78]:
'\n'
In [79]:
b = r'\n' # the string \n
b
Out[79]:
'\\n'

Triple Quoted Strings

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.

In [80]:
a = """
This string is on multiple lines.
It can be very long if you wish.
"""

Strings are Immutable

Unlike C, Strings are immutable meaning you cannot change them once they are created.

In [81]:
a = 'My test string'
a[0]
Out[81]:
'M'
In [82]:
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

String Formatting

Python 3.6 has three methods of string formatting: % operator, the format method, and f strings (new in Python 3.6)

In [83]:
first_name = 'Mark'
last_name = 'Lavin'
'%s %s' % (first_name, last_name)
Out[83]:
'Mark Lavin'
In [84]:
'{} {}'.format(first_name, last_name)
Out[84]:
'Mark Lavin'
In [85]:
f'{first_name} {last_name}'
Out[85]:
'Mark Lavin'

% Operator

The % operator uses the same string formatting as printf in C.

  • 'd' Signed integer decimal.
  • 'i' Signed integer decimal.
  • 'o' Signed octal value.
  • 'x' Signed hexadecimal (lowercase).
  • 'X' Signed hexadecimal (uppercase).
  • 'e' Floating point exponential format (lowercase).
  • 'E' Floating point exponential format (uppercase).
  • 'f' Floating point decimal format.
  • 'F' Floating point decimal format.
  • 'r' String (converts any Python object using repr()).
  • 's' String (converts any Python object using str()).
In [86]:
a = 10
b = 37.0
'%i %i' % (a, b)
Out[86]:
'10 37'
In [87]:
'%f %f' % (a, b)
Out[87]:
'10.000000 37.000000'
In [88]:
'%s %s' % (a, b)
Out[88]:
'10 37.0'

Formatting with Mappings

You can also used named mappings while formatting strings.

In [89]:
'%(last)s, %(first)s' % {'first': 'Mark', 'last': 'Lavin'}
Out[89]:
'Lavin, Mark'

More on mappings coming up.

Format Method

This method was introduced as part of (PEP 3101)[https://www.python.org/dev/peps/pep-3101/].

In [90]:
# positional arguments
'{0} {1}'.format('Hello', 'World')
Out[90]:
'Hello World'
In [91]:
# named arguments
'{first} {second}'.format(second='World', first='Hello')
Out[91]:
'Hello World'

f Strings

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.

In [92]:
price = 10
name = 'book'
f'The {name} costs ${price:0.2f}'
Out[92]:
'The book costs $10.00'

String Concatenating

Stings can be combined with the + operator or by using string formatting. Note that the + operator will not change type.

In [93]:
a = 'test'
b = 'string'
c = 10
a + b
Out[93]:
'teststring'
In [94]:
'%s %s' % (a, b)
Out[94]:
'test string'
In [95]:
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
In [96]:
'%s %s' % (a, c)
Out[96]:
'test 10'

String Methods

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.

In [97]:
a = 'my test string'
a.upper()
Out[97]:
'MY TEST STRING'
In [98]:
a
Out[98]:
'my test string'

Additional String Methods

In [99]:
'test'.capitalize()
Out[99]:
'Test'
In [100]:
'test'.endswith('a')
Out[100]:
False
In [101]:
'test'.find('e')
Out[101]:
1
In [102]:
'test'.lower()
Out[102]:
'test'
In [103]:
'test'.replace('t', 'b')
Out[103]:
'besb'
In [104]:
'a b c'.split()
Out[104]:
['a', 'b', 'c']
In [105]:
'test'.startswith('i')
Out[105]:
False
In [106]:
'test string'.title()
Out[106]:
'Test String'

Unicode

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.

In [157]:
'☃' == '\u2603'
Out[157]:
True

Byte Strings

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.

In [160]:
heart = b'\xe2\x9d\xa4'
heart.decode()
Out[160]:
'❤'

Lists

List define a zero-indexed squence of objects.

In [107]:
[1, 2, 3]
Out[107]:
[1, 2, 3]

Items in a list do not need to be the same type. Lists can also be nested.

In [108]:
[1, 'a', [2, 'b']]
Out[108]:
[1, 'a', [2, 'b']]

Accessing List Items

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.

In [109]:
a = [1, 2, 3]
a[0]
Out[109]:
1
In [110]:
a[0:1]
Out[110]:
[1]
In [111]:
a[-1]
Out[111]:
3

Lists Functions

Check out the full list here: http://docs.python.org/library/stdtypes.html#mutable-sequence-types

In [112]:
[1, 2, 3].append(4) # Inserts value at the end of the list
In [113]:
[1, 2, 3].extend([4, 5]) # Appends iterable to the end of the list
In [114]:
[1, 2, 3].pop() # Returns first item and removes from the list
Out[114]:
3
In [115]:
[1, 2, 3].count(1) # Returns the number of values which match
Out[115]:
1
In [116]:
[1, 2, 3].index(2) # Returns the first index where value is found`
Out[116]:
1
In [117]:
[1, 2, 3].insert(1, 4) # Inserts 4 to position 1
In [118]:
[1, 2, 3].reverse() # Reverses the order of items

List as a Stack

It's easy to use Python lists as a stack (last-in, first-out).

In [119]:
a = [1, 2, 3]
a.append(4)
a
Out[119]:
[1, 2, 3, 4]
In [120]:
a.pop()
Out[120]:
4
In [121]:
a
Out[121]:
[1, 2, 3]
In [122]:
a.pop()
Out[122]:
3
In [123]:
a
Out[123]:
[1, 2]

Tuples

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.

In [124]:
a = (1, 2, 3)

Beware of the Trailing Comma

Parentheses around a tuple are optional. This allows for handy things like swapping values and unpacking tuples or lists. But if you type

In [125]:
a = 1, # a is a tuple (1,)
a
Out[125]:
(1,)

Unpacking Lists and Tuples

It's possible to unpack a list or tuple:

In [126]:
a, b, c = [1, 2, 3]
a
Out[126]:
1
In [127]:
b
Out[127]:
2
In [128]:
c
Out[128]:
3

Simple Variable Swap

Using a similar syntax you can easily swap to variables:

In [129]:
a = 1
b = 2
a, b = b, a
a
Out[129]:
2
In [130]:
b
Out[130]:
1

Advanced Unpacking

Python 3 allows for more advanced unpacking syntax. This allows for unpacking only part of a list or tuple.

In [131]:
head, *rest, tail = ['a', 'b', 'c', 'd', 'e']
head
Out[131]:
'a'
In [132]:
tail
Out[132]:
'e'
In [133]:
rest
Out[133]:
['b', 'c', 'd']

Dictionaries

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:

In [134]:
a = {'key': 'value'}
a['key']
Out[134]:
'value'
In [135]:
a['new-key'] = 'new-value'
a
Out[135]:
{'key': 'value', 'new-key': 'new-value'}

Using Dictionaries

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:

In [136]:
'key' in a
Out[136]:
True
In [137]:
'missing' in a
Out[137]:
False
In [138]:
a['missing']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-138-b548a192f37f> in <module>()
----> 1 a['missing']

KeyError: 'missing'
In [139]:
a.get('missing')
In [140]:
a.get('missing', 'default')
Out[140]:
'default'

Using Dictionaries (cont.)

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.

In [141]:
a.keys()
Out[141]:
dict_keys(['key', 'new-key'])
In [142]:
a.values()
Out[142]:
dict_values(['value', 'new-value'])
In [143]:
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

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.

In [144]:
a = set([1, 2, 3])
b = set([2, 4, 6])
a | b # union
Out[144]:
{1, 2, 3, 4, 6}
In [145]:
a & b # intersection
Out[145]:
{2}
In [146]:
a - b # difference
Out[146]:
{1, 3}
In [147]:
a ^ b # symmetric difference
Out[147]:
{1, 3, 4, 6}

Set Comparsions

Comparison operators can be used to check for subsets.

In [148]:
a = set([1, 2, 3])
b = set([1 ,2, 3, 6])
a <= b # Is subset?
Out[148]:
True
In [149]:
a < b # Is strict (non-equal) subset
Out[149]:
True
In [150]:
a >= b # Is superset?
Out[150]:
False
In [151]:
a > b # Is strict (non-equal) superset
Out[151]:
False

Set Literals

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.

In [152]:
a = {1, 2, 3}

Unpacking Positional Arguments

Lists and tuples can be unpacked to fill in positional arguments for a function call using *.

In [153]:
def add(x, y):
    return x + y

data = (1, 2)
add(*data)
Out[153]:
3

Unpacking Keyword Arguments

Dictionaries can be used to fill arguments using **.

In [154]:
def subtract(x, y):
    return x - y

data = {'y': 1, 'x': 3}
subtract(**data) # same as subtract(y=1, x=3)
Out[154]:
2

Built-in Constants

Python has built in logical constants: True, False, None

Notes on Truth

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

Up Next

Creating your own classes!