Section 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.
Checkpoint 9.4.1.
Which of the following correctly uses indexing? Assume that a
is a list or string. Select as many as apply.
w = [a]
No, due to the way the code was written it creates a list. This list would have one element which is the value assigned to the variable a.
y = a[]
Though this tries to use indexing, it does not specify what element should be taken from a.
x = [8]
No, this is an example of creating a list.
t = a[0]
Yes, this will using indexing to get the value of the first element of a.
You have attempted
of
activities on this page.