Accessing Items

Lists

A list datatype represents a numbered, ordered collection of items.

Characteristics

A list has square brackets ([]) on the extremities, and comma separated items inside.

A list may contain zero or more items. A list can contain items of any datatype, but as a best practice, all items in a list should share a datatype and structure.

my_empty_list = []
print(type(my_empty_list))
<class 'list'>
symbols = ["MSFT", "AAPL", "GOOGL", "AMZN", "NFLX"]
print(type(symbols))
print(symbols)
<class 'list'>
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX']

We access items in a list by their numeric position, called the index. In Python (and most other languages), indices are zero-based, meaning the index of the first item is zero. We use square brackets ([]) to denote which item we would like to access:

print(symbols[0])
print(symbols[1])
print(symbols[2])
print(symbols[3])
print(symbols[4])
#print(symbols[5]) #> ERROR (IndexError)
MSFT
AAPL
GOOGL
AMZN
NFLX

We can use a negative one to dynamically reference the last item in the list (regardless of how many there are):

print(symbols[-1])
NFLX

List Slicing

It is possible to access a subset of the items in order by denoting the numeric position of the first and last item you would like:

print(symbols[0:1])
print(symbols[0:2])
print(symbols[0:3])
['MSFT']
['MSFT', 'AAPL']
['MSFT', 'AAPL', 'GOOGL']

To access a subset of the items based on some condition, we will use a filter operation instead.

Operations

Here are some additional common list operations.

Adding items, using the append method:

print(symbols)

symbols.append("NVDA")

print(symbols)
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX']
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX', 'NVDA']

Updating an item, by its numeric position:

print(symbols)

symbols[-1] = "UPDATED"

print(symbols)
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX', 'NVDA']
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX', 'UPDATED']

Removing an item, by its numeric position:

print(symbols)

del symbols[-1]

print(symbols)
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX', 'UPDATED']
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX']

Removing an item, using the remove method:

flavors = ["vanilla", "chocolate", "strawberry"]

flavors.remove("chocolate")

print(flavors)
['vanilla', 'strawberry']

Concatenating lists:

all_symbols = symbols + ["SPOT", "NVDA"]
print(all_symbols)
['MSFT', 'AAPL', 'GOOGL', 'AMZN', 'NFLX', 'SPOT', 'NVDA']

Length Checking

We will commonly ask how many items a list contains, using the len function:

len(symbols)
5

Inclusion Checking

We can use membership operators to check if an item is present in the list:

print("NFLX" in symbols)
print("NFLX" not in symbols)
True
False

Data Processing Operations

We will return to work with lists in much more detail, as we study list-based data processing techniques: