What are lists?

Similar to arrays in some other programming languages, lists in Python are used to store a set of elements under a single variable name. Each element can be accesses by using its index, which is simply an address that identifies the item’s place in the list. Elements of a list are defined inside the square brackets ([]) and are separated by commas.

Here is an example. The my_numbers = [5,3,2,7] statement will define the myNumbers list with four elements – 5,3,2,7. To access the first element of the list (the number 5), we can specify its index in the square brackets. Since indexes start from 0, to access the first element of the list, we would use the following statement: my_numbers[0]:

my_numbers = [5, 3, 2, 7]
print(my_numbers[0])

>>>
5
>>>

To get the last item in the list, we can use the -1 index:

print(my_numbers[-1])
>>>
7
>>>

We can slice up the lists this way:

print(my_numbers[:2])

>>>
[5, 3]
>>>

If we don’t specify the starting index, Python starts from the beginning of the list. Notice how the third element in the list (the number 2) wasn’t included in the output.

Another example:

print(my_numbers[1:3])

>>>
[3, 2]
>>>

As you can see from the output above, if we specify both indexes, we can get a subset of a list.

Geek University 2022