Lesson 29/48 ยท ๐Ÿ“ฆ Data Structures
๐Ÿ“ฆ Data StructuresLesson 29/48
Phase 5 ยท Data Structures25 min

Lists, Ordered Collections

Store and manipulate multiple values in a single variable

A list stores multiple values in order. Think of it as a shopping cart, you can add items, remove items, and look up any item by its position.
Creating and accessing listspython
numbers = [3, 1, 4, 1, 5, 9]
names = ["Alice", "Bob", "Charlie"]

print(numbers[0])    # 3  (first item)
print(numbers[-1])   # 9  (last item)
print(len(numbers))  # 6  (length)
print(numbers[1:4])  # [1, 4, 1]  (slice)
๐Ÿ”Code TracerStep 1 / 7
trace.py
1nums = [3, 1, 4, 1, 5]โ†
2nums.append(9)
3nums.sort()
4print(nums)
Variables
No variables yet
Step 1 / 7
Modifying listspython
fruits = ["apple", "banana"]

fruits.append("cherry")     # Add to end
fruits.insert(0, "avocado") # Insert at position
fruits.remove("banana")     # Remove by value
popped = fruits.pop()       # Remove & return last item
fruits.sort()               # Sort in place
print(fruits)
Common list operations:
  • list.append(x), add to end
  • list.insert(i, x), insert at index i
  • list.remove(x), remove first occurrence of x
  • list.pop(), remove and return last item
  • list.sort(), sort in place
  • sorted(list), return new sorted list
  • ๐ŸŒIn the Real World...

    Container logs come as lists of strings. Pod names, node IPs, deployment replicas, security group rules, all stored and manipulated as lists in cloud automation scripts.

    Practice Exercises

    0/2 solved
    Exercise 1 of 2medium
    โฑ 00:00

    Second Largest

    Write a function second_largest(numbers) that returns the second largest unique number in a list.
    Example: second_largest([3, 1, 4, 1, 5, 9, 2, 6]) โ†’ 6
    solution.py
    1 / 2
    Exercise 2 of 2medium
    โฑ 00:00

    Flatten a List

    Write a function flatten(nested) that takes a list of lists and returns a single flat list.
    Example: flatten([[1,2], [3,4], [5]]) โ†’ [1, 2, 3, 4, 5]
    solution.py
    2 / 2
    Solve all 2 exercises to unlock completion