In this lesson, we will learn about lists (also called arrays) in python. A list is a datatype. A list can contain multiple elements. Each element can be any data type including a list. The elements are separated by commas in between square brackets:
items = [“bread”, “chicken”, “eggs”]
price = [2, 5.34, 0.45]
Try printing items using print(). If you want to get an element in a list, you must enter that element number minus one. for example, for the first element, type:
For the third element, type;
Getting all the elements of a list
To get all the elements of a list, we can use the for loop. to do this we need to know the number of elements in the list. we can do this using:
Try using one of the lists at the start and run this code in python. It should print 3. Don’t forget to wrap it in a print function! With this knowledge, try making a for loop for this. It should look like the following:
for i in range(len(items)):
Using the lists from the start of this lesson, I will show you an example of a real-world application. Let’s say we want to buy 4 loaves of bread, 2 chickens and 24 eggs. How could we calculate the total price? We could multiply the prices by the amount of each item one by one but if we had many more items, that would become unreasonable. I will show you how to use for loops to do this. First, we can define a list items bought:
items_bought = [4, 2, 24]
Next, we create a variable total_price and set it to zero:
total_price = 0
Next, we need to use a for loop until and increase the price by the number of items sold times the price of each item. try to implement this yourself in python. Keep reading to find the code for this algorithm.
Try it yourself
Below is the code for this algorithm. Try adding new items (carrots, apples etc.) along with prices and numbers of each one bought (items_bought). Also, try changing the price of objects. Observe how that affects the output.
Now that you know some of the basic functions of lists, your python arsenal has increased exponentially! If you have any questions, please comment them or ask them here. See you in the next lesson!