Square brackets come in opening([) and closing pairs (]). They are
used to enclose lists and to access a specific index in a list.
Index
A non-negative number given to each element in a list to uniquely identify it.
Declaring Lists
Declaring a list in Python is easy. All you have to do is enclose the
list within square brackets and separating each item with a
comma and in most cases, assign it to a variable. Python makes it very
easy to print the entire list - simply print the variable that holds
the string.
# Declaring a List
list = ['DBZ', 'Arrested Development', 'The Simpsons', 'Breaking Bad']
# Printing to console
print(list)
['DBZ', 'Arrested Development', 'The Simpsons', 'Breaking Bad']
List Indices
Every element in a list is assigned non-negative integer called an
index. The first element is given an index of 0. This is a
point of a lot of confusion for students as they'll start counting the
elements from one. Below is a visual representation of a list with the
indices.
We can use the index of an element to access its value in the following manner:
# Declaring a List
list = ['DBZ', 'Arrested Development', 'The Simpsons', 'Breaking Bad']
# Accessing Elements with Indices
print(list[0])
print(list[1])
print(list[2])
print(list[3])
DBZ
Arrested Development
The Simpsons
Breaking Bad
Accessing Elements in a List
We can access elements in a list by supplying the list name followed by the index of the desired element enclosed in square brackets. We can even even call methods after accessing a specific element as shown below:
> ['DBZ', 'Arrested Development', 'The Simpsons', 'Breaking Bad']
> Arrested Development
> ARRESTED DEVELOPMENT
Using List Elements in Strings
We can also use values stored in a list in a string in a formatted string. Notice the difference in output when you supply the list name by itself as opposed to the list name with an index.
shows = ['DBZ', 'Arrested Development', 'The Simpsons', 'Breaking Bad']
# Different parts of a list.
print(f'My favorite shows are {shows}.')
# Insert newline
print('\n')
print(f'My favorite show is {show[1]}!')
My favorite shows are ['DBZ', 'Arrested Development', 'The Simpsons', 'Breaking Bad'].
My favorite show is Arrested Development!