๐Ÿ Lesson 8: Lists

Keep many things together, in order

โ† Back to Python Basics

๐Ÿ“‹ What is a list?

A list holds many values in a single variable, kept in order. You write it with square brackets [ ], separating items with commas.

fruits = ["apple", "banana", "cherry"] numbers = [10, 20, 30, 40] mixed = ["Maya", 11, True]

๐Ÿ“ Reading items by index

Just like strings, lists are numbered from 0:

fruits = ["apple", "banana", "cherry"] print(fruits[0]) # apple print(fruits[2]) # cherry print(fruits[-1]) # cherry (last item) print(len(fruits)) # 3

โœ๏ธ Changing and adding items

fruits = ["apple", "banana"] fruits[0] = "mango" # change an item fruits.append("cherry") # add to the end fruits.insert(1, "kiwi") # insert at position 1 print(fruits) # ['mango', 'kiwi', 'banana', 'cherry']

๐Ÿ—‘๏ธ Removing items

fruits = ["apple", "banana", "cherry"] fruits.remove("banana") # remove by value last = fruits.pop() # remove & return the last item print(fruits) # ['apple'] print(last) # cherry

๐Ÿ” Looping through a list

This is where lists shine โ€” a for loop visits every item:

scores = [90, 85, 100] for s in scores: print(f"Score: {s}")

๐Ÿ› ๏ธ Handy list tools

nums = [3, 1, 4, 1, 5] print(len(nums)) # 5 how many items print(sum(nums)) # 14 add them all print(max(nums)) # 5 biggest print(min(nums)) # 1 smallest nums.sort() # put in order print(nums) # [1, 1, 3, 4, 5] print("apple" in fruits) # True/False โ€” is it there?

โœ… What you learned

  • Lists hold ordered collections in [ ].
  • Read items by index (starting at 0); [-1] is the last.
  • Add with .append() / .insert(), remove with .remove() / .pop().
  • Loop with for; use len, sum, max, min, sort, and in.