Lesson 2 • Intermediate

    Lists in Python

    Store and manage multiple values in a single variable using Python lists.

    What You'll Learn in This Lesson

    • What a list is and why it's Python's most-used data structure
    • How to access items by index (including negative indexing)
    • How to add, remove, and change items in a list
    • How to slice lists to extract subsets
    • How to loop through lists and search for items
    • Useful list methods: sort, reverse, count, len

    1. What Are Lists?

    A list is a collection that stores multiple items in a single variable. Lists are ordered, changeable, and allow duplicate values.

    # Creating a list
    fruits = ["apple", "banana", "cherry"]
    # Lists use square brackets []

    Key Characteristics

    • Ordered — Items have a defined order (index 0, 1, 2...)
    • Mutable — You can add, remove, or change items
    • Allow duplicates — Same value can appear multiple times
    • Mixed types — Can hold strings, numbers, booleans, etc.

    2. Creating Lists

    TypeExampleDescription
    Empty listmy_list = []Start with nothing
    Strings["a", "b", "c"]List of text values
    Numbers[1, 2, 3, 4, 5]List of integers
    Mixed[1, "hello", True]Different types together
    Nested[[1, 2], [3, 4]]Lists inside lists

    Try It: Creating Lists

    Different ways to create lists

    Try it Yourself »
    Python
    # Different ways to create lists
    
    # Empty list
    my_list = []
    print("Empty:", my_list)
    
    # List with strings
    fruits = ["apple", "banana", "cherry"]
    print("Fruits:", fruits)
    
    # List with numbers
    numbers = [10, 20, 30, 40, 50]
    print("Numbers:", numbers)
    
    # Mixed types
    mixed = [1, "hello", True, 3.14]
    print("Mixed:", mixed)
    
    # How many items?
    print(f"Fruits has {len(fruits)} items")

    3. Accessing Items by Index

    Each item in a list has an index (position number). Python uses zero-based indexing — the first item is at index 0.

    # Index positions
    fruits = ["apple", "banana", "cherry", "date"]
    # 0 1 2 3
    # -4 -3 -2 -1
    CodeResultExplanation
    fruits[0]"apple"First item
    fruits[2]"cherry"Third item
    fruits[-1]"date"Last item (negative index)
    fruits[-2]"cherry"Second to last

    Try It: Accessing Items

    Use indexes to access list items

    Try it Yourself »
    Python
    fruits = ["apple", "banana", "cherry", "date"]
    
    # Positive indexing (from start)
    print("First item:", fruits[0])
    print("Second item:", fruits[1])
    print("Third item:", fruits[2])
    
    # Negative indexing (from end)
    print("Last item:", fruits[-1])
    print("Second to last:", fruits[-2])
    
    # Get length of list
    print(f"Total items: {len(fruits)}")

    4. Changing List Items

    Lists are mutable — you can change items after creation by assigning a new value to a specific index.

    fruits = ["apple", "banana", "cherry"]
    fruits[1] = "blueberry" # Change banana to blueberry
    # Result: ["apple", "blueberry", "cherry"]

    Try It: Changing Items

    Modify items in a list

    Try it Yourself »
    Python
    colors = ["red", "green", "blue"]
    print("Original:", colors)
    
    # Change single item
    colors[0] = "yellow"
    print("After change:", colors)
    
    # Change last item
    colors[-1] = "purple"
    print("After another change:", colors)

    5. Adding Items to Lists

    MethodWhat It DoesExample
    .append(item)Add item to the endfruits.append("mango")
    .insert(i, item)Add item at position ifruits.insert(1, "pear")
    .extend(list)Add all items from another listfruits.extend(["kiwi", "lime"])

    Try It: Adding Items

    Add items with append, insert, and extend

    Try it Yourself »
    Python
    fruits = ["apple", "banana"]
    print("Start:", fruits)
    
    # append - add to end
    fruits.append("cherry")
    print("After append:", fruits)
    
    # insert - add at specific position
    fruits.insert(1, "blueberry")
    print("After insert at 1:", fruits)
    
    # extend - add multiple items
    fruits.extend(["date", "elderberry"])
    print("After extend:", fruits)

    6. Removing Items from Lists

    MethodWhat It DoesExample
    .remove(item)Remove first match by valuefruits.remove("banana")
    .pop()Remove and return last itemlast = fruits.pop()
    .pop(i)Remove and return item at index ifirst = fruits.pop(0)
    .clear()Remove all itemsfruits.clear()
    del list[i]Delete item at index idel fruits[0]

    Try It: Removing Items

    Remove items with remove, pop, and del

    Try it Yourself »
    Python
    fruits = ["apple", "banana", "cherry", "banana", "date"]
    print("Start:", fruits)
    
    # remove - by value (first occurrence only)
    fruits.remove("banana")
    print("After remove banana:", fruits)
    
    # pop - remove and return last item
    last = fruits.pop()
    print(f"Popped: {last}, Remaining:", fruits)
    
    # pop(0) - remove first item
    first = fruits.pop(0)
    print(f"Popped first: {first}, Remaining:", fruits)

    7. List Slicing — Get a Range of Items

    Slicing lets you get a portion of a list using the syntaxlist[start:end].

    # Syntax: list[start:end:step]
    # start = where to begin (included)
    # end = where to stop (excluded)
    # step = how many to skip (optional)
    CodeResultMeaning
    nums[1:4][1, 2, 3]Index 1 to 3 (4 excluded)
    nums[:3][0, 1, 2]First 3 items
    nums[3:][3, 4, 5]From index 3 to end
    nums[-2:][4, 5]Last 2 items
    nums[::2][0, 2, 4]Every 2nd item
    nums[::-1][5, 4, 3, 2, 1, 0]Reversed list

    Try It: List Slicing

    Extract portions of a list

    Try it Yourself »
    Python
    nums = [0, 1, 2, 3, 4, 5]
    print("Original:", nums)
    
    # Get a range
    print("nums[1:4]:", nums[1:4])   # [1, 2, 3]
    
    # From start / to end
    print("nums[:3]:", nums[:3])     # [0, 1, 2]
    print("nums[3:]:", nums[3:])     # [3, 4, 5]
    
    # Negative slicing
    print("Last 2:", nums[-2:])      # [4, 5]
    
    # With step
    print("Every 2nd:", nums[::2])   # [0, 2, 4]
    print("Reversed:", nums[::-1])   # [5, 4, 3, 2, 1, 0]

    8. Looping Through Lists

    Use a for loop to go through each item:

    MethodUse WhenExample
    for item in list:You just need the itemsfor fruit in fruits:
    for i, item in enumerate(list):You need index + itemfor i, fruit in enumerate(fruits):

    Try It: Looping Through Lists

    Iterate over list items

    Try it Yourself »
    Python
    fruits = ["apple", "banana", "cherry"]
    
    # Simple loop - just items
    print("Simple loop:")
    for fruit in fruits:
        print(fruit)
    
    # With index using enumerate
    print("\nWith index:")
    for i, fruit in enumerate(fruits):
        print(f"{i}: {fruit}")
    
    # Start counting from 1 instead of 0
    print("\nNumbered list:")
    for num, fruit in enumerate(fruits, start=1):
        print(f"{num}. {fruit}")

    9. Useful List Methods

    Method/FunctionWhat It DoesReturns
    len(list)Number of itemsInteger
    .sort()Sort ascending (modifies list)None
    .sort(reverse=True)Sort descendingNone
    .reverse()Reverse the orderNone
    .count(x)Count occurrences of xInteger
    .index(x)Find position of xInteger
    .copy()Create a copyNew list
    sum(list)Sum of numbersNumber
    min(list) / max(list)Smallest / largest valueItem

    Try It: List Methods

    Common list operations

    Try it Yourself »
    Python
    numbers = [5, 2, 8, 1, 9, 2, 5]
    print("Original:", numbers)
    
    # Sorting
    numbers.sort()
    print("Sorted:", numbers)
    
    numbers.sort(reverse=True)
    print("Descending:", numbers)
    
    # Counting
    print(f"Count of 5: {numbers.count(5)}")
    
    # With number lists
    nums = [10, 20, 30, 40]
    print(f"Sum: {sum(nums)}")
    print(f"Min: {min(nums)}, Max: {max(nums)}")
    print(f"Average: {sum(nums) / len(nums)}")

    10. Checking if Item Exists

    Use in andnot in to check membership:

    Try It: Membership Check

    Check if items exist in a list

    Try it Yourself »
    Python
    fruits = ["apple", "banana", "cherry"]
    
    # Check if item exists
    if "banana" in fruits:
        print("Yes, banana is in the list!")
    
    if "grape" not in fruits:
        print("No, grape is NOT in the list")
    
    # Practical use: safe removal
    item_to_remove = "orange"
    if item_to_remove in fruits:
        fruits.remove(item_to_remove)
    else:
        print(f"{item_to_remove} not found in list")

    11. List Comprehension (Advanced)

    List comprehension is a concise way to create lists in one line. It is more advanced but very powerful once you learn it.

    # Syntax
    [expression for item in iterable]
    # With condition
    [expression for item in iterable if condition]
    Traditional Loop
    squares = []
    for x in range(5):
        squares.append(x ** 2)
    # [0, 1, 4, 9, 16]
    List Comprehension
    squares = [x ** 2 for x in range(5)]
    # [0, 1, 4, 9, 16]

    Try It: List Comprehension

    Create lists with one-line expressions

    Try it Yourself »
    Python
    # Basic list comprehension
    squares = [x ** 2 for x in range(6)]
    print("Squares:", squares)
    
    # With condition - only even numbers
    evens = [x for x in range(10) if x % 2 == 0]
    print("Evens:", evens)
    
    # Transform items
    words = ["hello", "world", "python"]
    upper_words = [word.upper() for word in words]
    print("Uppercase:", upper_words)
    
    # Get lengths
    lengths = [len(word) for word in words]
    print("Lengths:", lengths)

    12. Common Mistakes to Avoid

    MistakeProblemSolution
    Index out of rangelist[10]Check len(list) first
    Forgetting 0-indexingExpecting first item at 1First item is at index 0
    Removing nonexistent item.remove("x")Check if x in list: first
    Aliasing instead of copyinglist2 = list1Use list2 = list1.copy()
    Using parentheses(1, 2, 3)Use square brackets [1, 2, 3]

    13. Practical Examples

    Example 1: Shopping Cart

    Shopping Cart

    Build a simple shopping cart

    Try it Yourself »
    Python
    # Simple shopping cart
    cart = []
    
    # Add items
    cart.append("Milk")
    cart.append("Eggs")
    cart.append("Bread")
    print("Cart:", cart)
    
    # Remove an item
    cart.remove("Milk")
    print("After removing Milk:", cart)
    
    # Check if item in cart
    if "Eggs" in cart:
        print("Don't forget the eggs!")

    Example 2: Grade Calculator

    Grade Calculator

    Calculate statistics from grades

    Try it Yourself »
    Python
    # Calculate average grade
    grades = [85, 90, 78, 92, 88]
    
    average = sum(grades) / len(grades)
    highest = max(grades)
    lowest = min(grades)
    
    print(f"Grades: {grades}")
    print(f"Average: {average:.1f}")
    print(f"Highest: {highest}")
    print(f"Lowest: {lowest}")

    Example 3: To-Do List

    To-Do List

    Manage tasks with a list

    Try it Yourself »
    Python
    # Simple to-do list
    todos = ["Buy groceries", "Clean room", "Study Python"]
    
    print("My To-Do List:")
    for i, task in enumerate(todos, start=1):
        print(f"{i}. {task}")
    
    # Mark first task as done (remove it)
    completed = todos.pop(0)
    print(f"\nCompleted: {completed}")
    
    # Add new task
    todos.append("Walk the dog")
    
    print("\nUpdated To-Do List:")
    for i, task in enumerate(todos, start=1):
        print(f"{i}. {task}")

    Summary: Quick Reference

    OperationSyntaxExample
    Create[item1, item2]fruits = ["apple", "banana"]
    Accesslist[index]fruits[0]
    Changelist[i] = newfruits[0] = "apricot"
    Add.append(item)fruits.append("cherry")
    Remove.remove(item)fruits.remove("banana")
    Slicelist[start:end]fruits[1:3]
    Lengthlen(list)len(fruits)
    Loopfor item in list:for fruit in fruits:
    Check existsitem in list"apple" in fruits
    🎉

    Lesson 7 complete — you've unlocked Python's most-used data structure!

    Lists are everywhere in Python — shopping carts, user records, game inventories, search results. You can now create, access, modify, slice, sort, and loop through them.

    🚀 Up next: Dictionaries — store data with named keys instead of position numbers, perfect for structured records like user profiles.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service