Methods and functions

Introduction to Python for Finance

Adina Howe

Instructor

Methods vs. Functions

Methods
  • All methods are functions
  • List methods are a subset of built-in functions in Python
Functions
  • Not all functions are methods
  • Used on an object
    • prices.sort()
  • Requires an input of an object
    • type(prices)
Introduction to Python for Finance

List Methods - sort

  • Lists have several built-in methods that can help retrieve and manipulate data
  • Methods can be accessed as list.method()

list.sort() sorts list elements in ascending order

prices = [238.11, 237.81, 238.91]

prices.sort()
print(prices)
[237.81, 238.11, 238.91]
Introduction to Python for Finance

Adding to a list with append and extend

list.append() adds a single element to a list

months = ['January', 'February', 'March']

months.append('April')
print(months)
['January', 'February', 'March', 'April']

list.extend() adds each element to a list

months.extend(['May', 'June', 'July'])

print(months)
['January', 'February', 'March', 'April', 'May', 'June', 'July']
Introduction to Python for Finance

Useful list methods - index

list.index(x) returns the lowest index where the element x appears

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
months.index('February')
1
print(prices[1])
237.81
Introduction to Python for Finance

More functions ...

  • min(list): returns the smallest element

  • max(list): returns the largest element

Introduction to Python for Finance

Find the month with smallest CPI

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
# Identify min price
min_price = min(prices)

# Identify min price index min_index = prices.index(min_price)
# Identify the month with min price min_month = months[min_index] print(min_month)
February
Introduction to Python for Finance

Let's practice!

Introduction to Python for Finance

Preparing Video For Download...