Create lists using square brackets and commas. Lists can contain any type of variable/data.
company1 = "APPL" company2 = "MMM" company3 = "MSFT" list_of_nums = [9, 43, 75, 14, 2019] list_of_strings = ['this', 'that', 'hello world'] list_of_variables = [company1, company2, company3] list_of_booleans = [True, False, False, True] list_of_mixed = [9, 'this', company1, True] print(list_of_nums) print(list_of_strings) print(list_of_variables) print(list_of_booleans) print(list_of_mixed)
[9, 43, 75, 14, 2019] ['this', 'that', 'hello world'] ['APPL', 'MMM', 'MSFT'] [True, False, False, True] [9, 'this', 'APPL', True]
Lists can even contain other lists
list_of_lists = [list_of_nums, list_of_variables] list_of_lists
[[9, 43, 75, 14, 2019], ['APPL', 'MMM', 'MSFT']]
Lists can even be defined as empty.
empty_list = 
Adding to lists#
Suppose we have a list of competitors, and we want to add more tickers to that list.
# starting point competitors = ['AAPL', 'MSFT', 'TSLA'] # We could just add the lists: more_competitors = ['AMZN', 'FB'] all_competitors = competitors + more_competitors print(all_competitors) # Another way to add to lists is to use the append method. all_competitors.append('SNAP') print(all_competitors)
['AAPL', 'MSFT', 'TSLA', 'AMZN', 'FB'] ['AAPL', 'MSFT', 'TSLA', 'AMZN', 'FB', 'SNAP']
You can access a specific element in a list by indexing the numerical position:
Here is an example using the all_competitors list that we defined earlier.
Why does this give us the second element? Because in Python, the index starts at zero.
However, to index the last element in a list:
Here we access a specific value and store it in a new variable called
the_one_i_want = all_competitors print(all_competitors) print(the_one_i_want)
['AAPL', 'MSFT', 'TSLA', 'AMZN', 'FB', 'SNAP'] TSLA
To grab a range of values, use the
comp_subset = all_competitors[0:2] comp_subset
Notice how the endpoints work. There are two elements in
comp_subset, coming from list positions 0 and 1. The third element in the list (element
) is not included in
When one side of the
: does not have a number, Python infers “from the beginning” or “until the end”.
['AAPL', 'MSFT', 'TSLA'] ['FB', 'SNAP']
.append(), there are other functions (usually called methods) that we can do with lists.
If we want to know how many items there are in a list, we can use
list_of_nums = [9, 43, 75, 14, 2019] list_length = len(list_of_nums) list_length
We can also remove elements from a list and store them in a new variable. The following code removes the last item from the list and stores it in the
list_of_nums = [9, 43, 75, 14, 20, 19, 54, 98, 4] x = list_of_nums.pop() print(x) print(list_of_nums)
4 [9, 43, 75, 14, 20, 19, 54, 98]
Similarly, we can remove the first element (remember indexing starts at 0), third element, etc.
y = list_of_nums.pop(0) z = list_of_nums.pop(2) print(y) print(z) print(list_of_nums)
9 14 [43, 75, 20, 19, 54, 98]
Just remember that after every
.pop() reference the list is shortened.