Lists in Python

Introduzione a Python per la finanza

Adina Howe

Instructor

Lists - square brackets [ ]

months = ['January', 'February', 'March', 'April', 'May', 'June']
Introduzione a Python per la finanza

Python is zero-indexed

list_figure

Introduzione a Python per la finanza

Subset lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[0]
'January'
months[2]
'March'
Introduzione a Python per la finanza

Negative indexing of lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[-1]
'June'
months[-2]
'May'
Introduzione a Python per la finanza

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']
Introduzione a Python per la finanza

Extended slicing with lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[3:]
['April', 'May', 'June']
months[:3]
['January', 'February', 'March']
Introduzione a Python per la finanza

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']
Introduzione a Python per la finanza

Let's practice!

Introduzione a Python per la finanza

Preparing Video For Download...