Let's make a grocery list with Python with carrots, pumpkins, and pasta. We could use a string. However, Python has something called a list, which is better for our job. You'll see why below.
A list is surrounded by brackets ( [ and ] ) and can have multiple comma-separated items which can be anything. Let's turn our grocery list into an actual list:
groceryStr = "carrots, pumpkins, pasta"
groceries = ["carrots","pumpkins","pasta"]
The list requires more typing. However, it has many advantages. Let's try to get the second item of each "list". To get the second item of groceries
, we use groceries[1]
. To get the second item from groceryStr
, we have to look at it, which is a big no-no in programming, because the computer can't run it on it's own.
Wait! Aren't we trying to get the second item of the list? Yes, but Python uses something called zero-indexing, meaning that the first item is 0, the second is 1, etc. Here's Python's idea of a list:
["carrots", "pumpkins", "pasta"]
| | | |
0 1 2 3
As you can see from the above diagram, Python is numbering the spaces between the items, not the items themselves. The reason for this is because Python wants to make it easy for us to select parts of a list.
Let's try to select the first two items in our list:
This selects everything from the 0th index to the 2nd index.
Python also places negative indexes:
["carrots", "pumpkins", "pasta"]
| | |
-3 -2 -1
If we select groceries[-2]
Python would give us "pumpkins". However, if we select groceries[-3:-2]
it would give ["carrots"]
Adding, Changing, and Removing Items
What if we realized we needed eggs as well? To add an item to a list, we use the .append(item)
method. This will append the item to the end of a list. Example:
groceries.append("eggs")
print(groceries) # ["carrots","pumpkins","pasta","eggs"]
What if we need to change pumpkins to 2 pumpkins? We can do that by setting groceries[1] as if it were a variable:
groceries[1] = "2 pumpkins"
print(groceries) # ["carrots","2 pumpkins","pasta","eggs"]
To remove the last item from a list, we use the .pop()
method. You can also give the .pop()
method an index of an item to delete. We can also remove any item from a list with the del
keyword as well.
del groceries[1]
print(groceries) # ["carrots","pasta","eggs"]
groceries.pop()
print(groceries) # ["carrots","pasta"]
We can use the in
keyword to check if something is in a list. Example:
print("a" in [1,2,3]) # False
print(1 in [1,2,3]) # True
To convert something to a list, we use the list()
function.