6.4. Disambiguating []: creation vs indexing

Square brackets [] are used in quite a few ways in python. When you’re first learning how to use them it may be confusing, but with practice and repetition they’ll be easy to incorporate!

You have currently encountered two instances where we have used square brackets. The first is creating lists and the second is indexing. At first glance, creating and indexing are difficult to distinguish. However, indexing requires referencing an already created list while simply creating a list does not.

In the code above, a new list is created using the empty brackets. Since there’s nothing in it though, we can’t index into it.

In the code above, you’ll see how, now that we have elements inside of new_lst, we can index into it. In order to extract an element of the list, we do use [], but we first have to specify which list we are indexing. Imagine if there was another list in the activecode. How would python know which list we want to index into if we don’t tell it? Additionally, we have to specify what element we want to extract. This belongs inside of the brackets.

Though it may be easier to distinguish in this above activecode, below may be a bit more difficult.

Here, we see a list called lst being assigned to a list with one element, zero. Then, we see how n_lst is assigned the value associated with the first element of lst. Dispite the variable names, only one of the above variables is assigned to a list. Note that in this example, what sets creating apart from indexing is the reference to the list to let python know that you are extracting an element from another list.

You have attempted of activities on this page