Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • define a list and create one correctly
  • access elements using index
  • update list values
  • explain why lists are useful for grouped data

What is a list?

  • A list is an ordered, mutable collection.
  • Ordered means elements have positions.
  • Mutable means elements can be changed after creation.
Examples:
marks = [78, 85, 91]
names = ["Asha", "Ravi", "Mira"]
mix = [10, "pen", 3.5, True]

Why lists matter

Without lists, storing many similar values becomes messy:
m1 = 78
m2 = 85
m3 = 91
With lists:
marks = [78, 85, 91]

Indexing

items = ["pen", "book", "bag"]
print(items[0])   # pen
print(items[2])   # bag
print(items[-1])  # bag
Rules:
  • first index is 0
  • negative index counts from end

Updating list values

items = ["pen", "book", "bag"]
items[1] = "notebook"
print(items)

Length and membership

nums = [10, 20, 30, 40]
print(len(nums))      # 4
print(20 in nums)     # True
print(99 in nums)     # False

Slicing lists

nums = [10, 20, 30, 40, 50]
print(nums[1:4])   # [20, 30, 40]
print(nums[:3])    # [10, 20, 30]
print(nums[::2])   # [10, 30, 50]

Exam hints and traps

  • list[index] gives one element
  • list[start:end] gives a new list slice
  • list is mutable, unlike string and tuple
  • invalid index raises IndexError

Quick practice

  1. Create a list of 5 colors.
  2. Print first and last element of a list.
  3. Replace third element of [1, 2, 3, 4] with 99.

Answer key

nums = [1, 2, 3, 4]
nums[2] = 99
print(nums)