1.3 Types#

Estimated time for this notebook: 20 minutes

We have seen that Python objects have a ‘type’:

type(5)
int

1.3.1 Floats and integers#

Python has two core numeric types, int for integer, and float for real number.

one = 1
ten = 10
one_float = 1.0
ten_float = 10.0

Zero after a point is optional. But the Dot makes it a float.

tenth = one_float / ten_float
tenth
0.1
type(one)
int
type(one_float)
float

The meaning of an operator varies depending on the type it is applied to!

print(one // ten)
0
one_float / ten_float
0.1
print(type(one / ten))
<class 'float'>
type(tenth)
float

The divided by operator when applied to floats, and integers means divide by for real numbers.

The // operator means divide and then round down

10 // 3
3
10.0 / 3
3.3333333333333335
10 / 3.0
3.3333333333333335

There is a function for every type name, which is used to convert the input to an output of the desired type.

x = float(5)
type(x)
float
10 / float(3)
3.3333333333333335

I lied when I said that the float type was a real number. It’s actually a computer representation of a real number called a “floating point number”. Representing \(\sqrt 2\) or \(\frac{1}{3}\) perfectly would be impossible in a computer, so we use a finite amount of memory to do it.

N = 10000.0
sum([1 / N] * int(N))
0.9999999999999062

Supplementary material:

1.3.2 Strings#

Python has a built in string type, supporting many useful methods.

given = "James"
family = "Hetherington"
full = given + " " + family

So + for strings means “join them together” - concatenate.

print(full.upper())
JAMES HETHERINGTON

As for float and int, the name of a type can be used as a function to convert between types:

ten, one
(10, 1)
print(ten + one)
11
print(float(str(ten) + str(one)))
101.0

We can remove extraneous material from the start and end of a string:

"    Hello  ".strip()
'Hello'

Note that you can write strings in Python using either single (' ... ') or double (" ... ") quote marks. The two ways are equivalent. However, if your string includes a single quote (e.g. an apostrophe), you should use double quotes to surround it:

"James's Class"
"James's Class"

And vice versa: if your string has a double quote inside it, you should wrap the whole string in single quotes.

'"Wow!", said Bob.'
'"Wow!", said Bob.'

1.3.3 Lists#

Python’s basic container type is the list.

We can define our own list with square brackets:

[1, 3, 7]
[1, 3, 7]
type([1, 3, 7])
list

Lists do not have to contain just one type:

various_things = [1, 2, "banana", 3.4, [1, 2]]

We access an element of a list with an int in square brackets:

various_things[2]
'banana'
index = 0
various_things[index]
1

Note that list indices start from zero.

We can use a string to join together a list of strings:

name = ["James", "Philip", "John", "Hetherington"]
print("==".join(name))
James==Philip==John==Hetherington

And we can split up a string into a list:

"Ernst Stavro Blofeld".split(" ")
['Ernst', 'Stavro', 'Blofeld']
"Ernst Stavro Blofeld".split("o")
['Ernst Stavr', ' Bl', 'feld']

And combine these:

"->".join("John Ronald Reuel Tolkien".split(" "))
'John->Ronald->Reuel->Tolkien'

A matrix can be represented by nesting lists – putting lists inside other lists.

identity = [[1, 0], [0, 1]]
identity[0][0]
1

… but later we will learn about a better way of representing matrices.

1.3.4 Ranges#

Another useful type is range, which gives you a sequence of consecutive numbers. In contrast to a list, ranges generate the numbers as you need them, rather than all at once.

If you try to print a range, you’ll see something that looks a little strange:

range(5)
range(0, 5)

We don’t see the contents, because they haven’t been generatead yet. Instead, Python gives us a description of the object - in this case, its type (range) and its lower and upper limits.

We can quickly make a list with numbers counted up by converting this range:

count_to_five = range(5)
print(list(count_to_five))
[0, 1, 2, 3, 4]

Ranges in Python can be customised in other ways, such as by specifying the lower limit or the step (that is, the difference between successive elements). You can find more information about them in the official Python documentation.

1.3.5 Sequences#

Many other things can be treated like lists. Python calls things that can be treated like lists sequences.

A string is one such sequence type.

Sequences support various useful operations, including:

  • Accessing a single element at a particular index: sequence[index]

  • Accessing multiple elements (a slice): sequence[start:end_plus_one]

  • Getting the length of a sequence: len(sequence)

  • Checking whether the sequence contains an element: element in sequence

The following examples illustrate these operations with lists, strings and ranges.

print(count_to_five[1])
1
print("James"[2])
m
count_to_five = range(5)
count_to_five[1:3]
range(1, 3)
"Hello World"[4:8]
'o Wo'
len(various_things)
5
len("Python")
6
name
['James', 'Philip', 'John', 'Hetherington']
"John" in name
True
3 in count_to_five
True

1.3.6 Unpacking#

Multiple values can be unpacked when assigning from sequences, like dealing out decks of cards.

mylist = ["Hello", "World"]
a, b = mylist
print(b)
World
range(4)
range(0, 4)
zero, one, two, three = range(4)
two
2

If there is too much or too little data, an error results:

zero, one, two, three = range(7)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[52], line 1
----> 1 zero, one, two, three = range(7)

ValueError: too many values to unpack (expected 4)
zero, one, two, three = range(2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[53], line 1
----> 1 zero, one, two, three = range(2)

ValueError: not enough values to unpack (expected 4, got 2)

Python provides some handy syntax to split a sequence into its first element (“head”) and the remaining ones (its “tail”):

head, *tail = range(4)
print("head is", head)
print("tail is", tail)
head is 0
tail is [1, 2, 3]

Note the syntax with the *. The same pattern can be used, for example, to extract the middle segment of a sequence whose length we might not know:

one, *two, three = range(10)
print("one is", one)
print("two is", two)
print("three is", three)
one is 0
two is [1, 2, 3, 4, 5, 6, 7, 8]
three is 9