Lists in Python

Nhập môn Python cho Tài chính

Adina Howe

Professor

Lists - square brackets [ ]

months = ['January', 'February', 'March', 'April', 'May', 'June']
Nhập môn Python cho Tài chính

Python is zero-indexed

list_figure

Nhập môn Python cho Tài chính

Subset lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[0]
'January'
months[2]
'March'
Nhập môn Python cho Tài chính

Negative indexing of lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[-1]
'June'
months[-2]
'May'
Nhập môn Python cho Tài chính

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']
Nhập môn Python cho Tài chính

Extended slicing with lists

months = ['January', 'February', 'March', 'April', 'May', 'June']
months[3:]
['April', 'May', 'June']
months[:3]
['January', 'February', 'March']
Nhập môn Python cho Tài chính

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']
Nhập môn Python cho Tài chính

Let's practice!

Nhập môn Python cho Tài chính

Preparing Video For Download...