Lists

Example: Indexed


In [ ]:
list1 = [10, 12, 14, 16, 18]

print(list1[0])      # Index starts at 0

print(list1[-1])     # Last index at -1

Example: Slicable


In [ ]:
print(list1[0:3])    # Slicing: exclusive of end value
                     #  i.e. get i=(0, 1, .. n-1)

print(list1[3:])     # "slice from i=3 to end"

Example: Mutable & Mixed Data Types


In [ ]:
list1.append(20)
print(list1)

list1.extend([22,24,26])
print(list1)

list1[3]='squirrel'
print(list1)

list1.remove('squirrel')
print(list1)

list1.insert(3,16)
print(list1)

Tuples

Example: Immutable


In [ ]:
tuple1 = (10, 12, 14, 16, 18)
print(tuple1)
print(tuple1[0])
print(tuple1[1:3])
print(tuple1[3:])

tuple1.append(20)
print(tuple1)

Example: Tuples are faster


In [ ]:
%timeit tuple1=(10,12,14,16,18)
%timeit list1=[10,12,14,16,18]
#%timeit tuple1[3:]
#%timeit list1[3:]

Example: Unpacking Tuples


In [ ]:
tuple2 = 'Lucy','Ryan'
a, b = tuple2
print('{} is OK, {} is amazing!'.format(a, b))

b, a = a, b
print('{} is OK, {} is amazing!'.format(a, b))

In [ ]:
ages = [('Lucy', 25), ('Ryan', 24)]

for name, age in ages:
    print('{} is {}.'.format(name, age))

Example: Python is Call by value


In [ ]:
list2 = [list1, tuple1]
list1 = [1, 2 , 3]
print(list2)

Numpy Arrays

Example: How to use


In [ ]:
# To use numpy, we first have to import the package
import numpy as np

# Can convert a list to an array:
array1=np.array(list1)
print(array1)


# Can make an evenly spaced array between 2 values using linspace or arange.
# linspace takes the number of points to use as an argument and returns floats by default
print(np.linspace(0, 10, 11))

# arange takes the spacing as an argument and returns the type given as the spacing, e.g.
print(np.arange(0, 11, 1.)) 
print(np.arange(0, 11, 1))

Example: Useful functions


In [ ]:
print('The average of array1 is', np.average(array1))
print('The sum of array1 is', np.sum(array1))

# Apply functions
print(np.exp(array1))
print(np.reciprocal(array1))

array2=np.array([float(array1[i]) for i in range(len(array1))])
a=np.reciprocal(array2)

print(np.reciprocal([float(array1[i]) for i in range(len(array1))]))

angles=np.array([0, np.pi/2., np.pi, 3*np.pi/4.])
np.sin(angles)

Example: 2d Arrays


In [ ]:
M1 = np.array([[2,3],[6,3]])
M2 = np.array([[5,6],[2,9]])

print('M1:')
print(M1)

print('M2:')
print(M2)

In [ ]:
M3 = M1 * M2            # Element-wise multiplication
print(M3, '\n')

M4 = np.dot(M1, M2)     # Matrix multiplication
print(M4)

Example: Creating an array from a file


In [ ]:
premier_league_data = np.loadtxt('example.csv')
print(premier_league_data)
print(type(premier_league_data[0][0]))

Dictionaries

Example: How to use


In [ ]:
price_table = {'apples': 50, 'pears': 60, 'bananas': 20}
print(price_table)

fruit = [('apples', 50), ('bananas', 20), ('pears', 60)]
price_table1 = dict(fruit)
print(price_table==price_table1)

# NOTE: the order when you define a dictionary doesn't matter, it's ordered with a hashtable not 
# with indexing lists and tuples

# To get a value out, you use square brackets but instead of an index, you use the key:
akey = 'apples'
print("The price of {} is {}p.".format(akey, price_table[akey]))

# Trying to use an index wouldn't work:
print(price_table[0])

In [ ]:
price_table.keys()

In [ ]:
# Example usage: 
shopping_list = [('apples', 50), ('bananas', 20)]
total = 0
for item, quantity in shopping_list:
    price = price_table[item]
    print('Adding {} {} at {}p each.'.format(quantity, item, price))
    total += price * quantity

print('Total shopping cost is £%.2f.' %(total/100.))

Example: Mutable


In [ ]:
price_table['kiwis']=30
print(price_table)

del price_table['bananas']
print(price_table)

price_table['apples']=25
print(price_table)

Example: Iterating


In [ ]:
# Iterating over the dictionary will iterate over its keys
for key in price_table:
    print("{} cost {}p".format(key, price_table[key]))

In [ ]:
# Or use the items method:
for key, val in price_table.items():
    print("{} cost {}p".format(key, val))

Functions

Example: Simple function


In [ ]:
def square_root(x):
    """Useful docstring: Calculates and returns square root of x"""
    i = x ** 0.5
    return i


x = 10
y = square_root(x)
print('The square root of {} is {}'.format(x, y))

# We can set a default value to the function 
def square_root(x=20):
    i = x ** 0.5
    return i


print(square_root())

# Loops, functions and appending
mylist = []
for i in range(1,5):
    mylist.append(square_root(i))
print(mylist)

Example: Arguments and mutability


In [ ]:
def update_integer(i):
    # attempt to update i (integers) are immutable
    i += 1

def update_list_end(arglist):
    arglist[-1] = 50   # Lists are mutable: updates args directly!

a = 1
update_integer(a)
print(a)

mylist = [0, 1, 2, 3, 4]
update_list_end(mylist)
print(mylist)

Plotting

Matplotlib

Example: Simple Plot


In [ ]:
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi)
y = np.sin(x)

fig = plt.figure(figsize=(12, 5))
ax = fig.add_subplot(111)
ax.plot(x, y,'o-')
ax.margins(0.1)
ax.set_title('2D plot')
ax.set_xlabel('$x$')
ax.set_ylabel(r'$sin(x)$')
ax.plot()

Example: Labels, ticks and other appenditories


In [ ]:
xtick_values = np.linspace(0, 2*np.pi, 5)
xtick_labels = ['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$',
             r'$2\pi$']
fig = plt.figure(figsize=(12, 5))
ax = fig.add_subplot(111); ax.plot(x, y,'-o')
ax.set_title('2D plot')
ax.margins(0.1)
ax.set_xlabel('$x$');  ax.set_ylabel(r'$sin(x)$')
ax.set_xticks(xtick_values)
ax.set_xticklabels(xtick_labels, fontsize=25);

Reading from and writing to files


In [ ]:
f1 = open('textfile.txt', 'r+')
print(f1.read())
f1.close()

In [ ]:
with open('textfile.txt', 'r+') as f1:
    print(f1.readline())
    print(f1.readline())

In [ ]:
with open('textfile.txt', 'r+') as f1:
    print(f1.readlines())

In [ ]:
with open('textfile.txt', 'r+') as f1:
    print(list(f1))

In [ ]:
with open('textfile.txt', 'r+') as f1:
    for line in f1:
        print(line)

In [ ]:
with open('textfile.txt', 'r+') as f1:
    f1.write('Hello')
    print(f1.readline())
    f1.write('Second Hello')
    print(f1.read())

In [ ]:
with open('textfile.txt', 'r+') as f1:
    print(f1.read())

In [ ]:
with open('textfile.txt', 'r+') as f1:
    lines = f1.readlines()
    del lines[-1]
    lines[2] = 'I have changed the third line\n'
    
with open('textfile.txt', 'w') as f1:
    f1.writelines(lines)
    f1.seek(0)
    
with open('textfile.txt') as f1:
    print(f1.read())