Lesson 10 · 10 of 20
Lists · Python
Keep several values in a Python list: read them by position, change them, loop over them with for and add them up with sum(), min() and max().

A list keeps several values in order, between square brackets and separated by commas. fruits holds four fruits and prices their four prices in the same order. print(fruits) shows the whole list and len(fruits) says how many items it has.
As with strings, every item has a position starting at 0: fruits[0] is apple and fruits[-1], the last one, is mango.
Unlike strings, lists can be changed: prices[3] = 0.99 replaces the mango's price (at position 3) with a cheaper one.
for fruit in fruits: goes through the list item by item, just as it went through the letters of a string. And in checks whether a value is in the list: "kiwi" in fruits is False.
For lists of numbers, sum() adds them up, min() gives the smallest and max() the largest. round(..., 2) keeps the total to two decimals.
Code · main.py
# A list keeps several values in order, between [ ].fruits = ["apple", "banana", "cherry", "mango"]prices = [0.40, 0.25, 0.10, 1.20]print(fruits)print("Items:", len(fruits))print("First:", fruits[0])print("Last:", fruits[-1])# A list can change: give a position a new value.prices[3] = 0.99print("A mango now costs", prices[3])# for goes through the list, one item at a time.for fruit in fruits: print("-", fruit)# in checks whether a value is in the list.print("Do we sell kiwis?", "kiwi" in fruits)# sum(), min() and max() work on lists of numbers.print("One of each costs", round(sum(prices), 2))print("Cheapest:", min(prices), "| Dearest:", max(prices))Output · python3 main.py
['apple', 'banana', 'cherry', 'mango'] Items: 4 First: apple Last: mango A mango now costs 0.99 - apple - banana - cherry - mango Do we sell kiwis? False One of each costs 1.74 Cheapest: 0.1 | Dearest: 0.99
Key points
- A list goes between
[ ]and can grow or change. items[0]is the first;items[-1]the last.len()gives the number of items.value in itemstells you whether it is there.sum(),min()andmax()work on lists of numbers.
Exercise
Make a list with a week's highest temperatures, then print the average (sum() divided by len()), the highest, the lowest and how many days went over 25 degrees.