Lists in Python

Introduction to Python for Finance

Adina Howe

Instructor

Lists - square brackets [ ]

months = ['January', 'February', 'March', 'April', 'May', 'June']
Introduction to Python for Finance

Python is zero-indexed

list_figure

Introduction to Python for Finance

Subset lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[0]
'January'
months[2]
'March'
Introduction to Python for Finance

Negative indexing of lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[-1]
'June'
months[-2]
'May'
Introduction to Python for Finance

Subsetting multiple list elements with slicing

Slicing syntax

# Includes the start and up to (but not including) the end
mylist[startAt:endBefore] 

Example

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[2:5]
['March', 'April', 'May']
months[-4:-1]
['March', 'April', 'May']
Introduction to Python for Finance

Extended slicing with lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[3:]
['April', 'May', 'June']
months[:3]
['January', 'February', 'March']
Introduction to Python for Finance

Slicing with Steps

# Includes the start and up to (but not including) the end
mylist[startAt:endBefore:step] 
months = ['January', 'February', 'March', 'April', 'May', 'June']
months[0:6:2]
['January', 'March', 'May']
months[0:6:3]
['January', 'April']
Introduction to Python for Finance

Let's practice!

Introduction to Python for Finance

Preparing Video For Download...