HomeCourseModule 06 › Lists — the everyday ordered collection

Lists — the everyday ordered collection

Module 06 · Data Structures9 min readBeginner

What you'll learn

  • Create and modify lists
  • Index, slice, and iterate
  • Use append, pop, insert, sort

Creating a list

fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30, 40, 50]
mixed = [1, "two", 3.0, True]
empty = []

Indexing

fruits[0]    # 'apple'  — Python starts at 0
fruits[1]    # 'banana'
fruits[-1]   # 'cherry' — negative indexes count from the end
fruits[-2]   # 'banana'

Slicing

nums = [10, 20, 30, 40, 50]
nums[1:4]     # [20, 30, 40]
nums[:3]      # [10, 20, 30]
nums[3:]      # [40, 50]
nums[:]       # [10, 20, 30, 40, 50]  — a copy
nums[::2]     # [10, 30, 50]  — every other one

Modifying

fruits = ["apple", "banana"]
fruits.append("cherry")        # add to the end
fruits.insert(0, "avocado")    # insert at index 0
fruits.remove("banana")        # remove by value
last = fruits.pop()            # remove and return last
fruits[0] = "apricot"          # replace by index

Useful list operations

len(fruits)         # how many items
"apple" in fruits   # True/False
sorted(numbers)     # returns a sorted copy
numbers.sort()      # sorts in place
numbers.reverse()
sum(numbers)        # 150
max(numbers)        # 50
min(numbers)        # 10

Walkthrough: track daily sales

Start with last week's numbers

daily = [1200, 950, 1340, 1100, 1600, 0, 0]   # Mon..Sun

This morning's sale comes in

daily.append(1450)        # Monday of week 2
print(daily)              # [1200, 950, 1340, 1100, 1600, 0, 0, 1450]

Print weekday totals only (drop the weekend)

weekdays = daily[:5]
print(sum(weekdays))      # 6190
⚠️ Lists are mutable
If you pass a list to a function and the function changes it, the original list is changed too. To pass a copy, use my_list[:] or list(my_list).

Key takeaways

  • Lists hold an ordered collection of anything.
  • Indexes start at 0; negative indexes count from the end.
  • append, pop, insert, remove, sort — the workhorses.
  • Lists are mutable — changes are in place unless you copy first.

Quick drill

Given nums = [5, 2, 8, 1, 9, 3], write one line each to:

  1. Get the average.
  2. Get the second-largest.
  3. Get a sorted list, descending.
  4. Get just the odd numbers.
📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.