9.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, both lines use square brackets, but one uses them for list creation and one uses them for indexing. You can differentiate them because with list creation there is nothing between the equal sign and the opening square bracket. On the left side of the equal sign is the variable that the list is being assigned to, and on the right side of the equal sign is the two square brackets with items in the list in between them. On the second line, the square brackets come immediately after a variable name, which tells you that they are indexing into that list variable. Because we have elements inside of new_lst, we can index into it. In order to extract an element of the list, we use [], but we first have to specify which list we are indexing. Additionally, we have to specify what element we want to extract. This index belongs inside of the brackets.

The code below shows that naming a variable as a list doesn’t make it a list.

Here, we see that the variable lst is assigned a list with one element, zero. Then, we see another variable called n_lst gets assigned the value associated with the first element of lst. Despite the variable names, only one of the above variables is assigned to a list.

You have attempted of activities on this page