Python Lists

4-13-2021

Today, we will be taking a look at lists in Python. Lists are a data structure in Python and many other programming languages which allow us to store several items in an indexed variables.


First we will look at how to create a list in Python by writing it out ourselves. Luckily, this is written very similarly to how an ordinary variable is created.


numbers=[1,2,3,4]

Let's notice a few things about how this is written. First, the list is surrounded by square brackets. Secondly, each item in the list the is separated by a comma. The left hand side of the equals sign is written essentially the same way as any other variable. Now, how can we access these items individually?


To do this, we must familiarize ourselves with array indexing. Each item in a list has an index, which is a number, associated with it's position in the list. Python, like most programming languages, uses indexing where the first item of a list has an index of zero. The index then increases by one at each position. For example in our list above, the number 4 has an index of 3, and the number 2 has an index of 1. And this is how we access them in Python:


numbers=[1,2,3,4]
print(numbers[1])


->2

So, we can use the index of each item to access individual items in our code. We can also add items onto the end of our list using the .append() method.


numbers=[1,2,3,4]
numbers.append(5)
print(numbers)

-> [1,2,3,4,5]

We can also remove items from the end with .pop().


numbers=[1,2,3,4]
numbers.pop();
print(numbers)

-> [1,2,3]

Now the last idea we will talk about today is looping through a list. We can use a for loop to iterate through each item of a list. We can do this by using the indeces of the list in a for loop, and running the loop the same number of times as the length of the list using the len() function.


numbers=[1,2,3,4]

for i in range(len(numbers)):
    print(numbers[i])

->1
->2
->3
->4

And there we go! An introduction to lists in Python. Try applying this to your own ideas for programs and seeing what you can come up with. There are many other functions you can do with lists as well, so make sure to do some research if you want to try and do something we didn't mention here.