Python Basics Tutorial 12 – Python Lists
Notes from the video ‘Python Programming | Python Tutorial 12 – Python Lists’:
A list is a sequence of values that’s ordered and changeable in Python.
Let’s try to create a list.
Defining a list is the same as a variable. Let’s say you want to create a list of primary colours.
Steps on creating a list in Python:
First, you type in the list name.
Then you type in the equal sign.
After that, things start to get different.
Each list is enclosed by square brackets. So, before you write the list, first start with an open square bracket.
primary_colours = [
Next, you key in the first value. In this case, it’s the string “blue”. You do the same thing for what you do for strings in general so you enclose it with quotation marks.
primary_colours = [“blue”
After that, you have to enter separate this first value from the next few values with a comma and a space.
primary_colours = [“blue”,
Then you type in the rest of the values. After you are done, you close the list with the square bracket.
primary_colours = [“blue”, “yellow”, “red”]
Index in Python Lists
Python numbers each element in the list automatically. Index is the position of the values within an order.
The first element in the list starts with the index 0, so the second element has the index 1 and the third element has the index 2 and so on.
Referring to elements in Python lists
If you want to refer to a particular element in the list, you first write the list name, which is primary_colours in this case, followed by the index number that’s enclosed in a square bracket.
So, if I want to print “red” which is the third element in the list, meaning it is index number 2, I can key in the code:
Python displays red.
Adding numbers to Python lists
Besides strings, you can also include numbers in list too. In fact, you can include a mix of numbers and strings in a list.
For example, we can include the number 5 as the fourth element in the list. As usual, you don’t have to enclose the numbers in strings.
So, this time if we were to enter the code:
Python would display the number 5.
You can also print the entire list if you want.
Let’s try printing the primary_colours list:
Python displays the entire list with the four elements, the strings “blue”, “yellow”, “red” and the number 5 in their original order enclosed by square brackets.