All labs · lesson 7 of 9

Pythonbeginner25 min

Python Lists and Loops

Master Python lists and learn how to use for loops to iterate through data.

Edit any code block and press Run (or Ctrl/⌘ + Enter, or Shift + Enter). The code runs in your browser, so there is nothing to install. The first run downloads the language once; later runs are instant.

Lists are one of the most powerful data structures in Python. Let’s learn how to use them!

Creating Lists

A list is a collection of items in a particular order.

Exercise 1: Your First List

# Create a list of your favorite fruits
fruits = ["apple", "banana", "orange", "mango"]
print("My fruits:", fruits)
print("First fruit:", fruits[0])
print("Number of fruits:", len(fruits))

For Loops

Loops let you repeat actions for each item in a list.

Exercise 2: Looping Through a List

# Loop through numbers and calculate squares
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    square = num ** 2
    print(f"{num} squared is {square}")

List Methods

Python provides many useful methods for working with lists.

Exercise 3: Modifying Lists

# Add and remove items from a list
shopping_list = ["milk", "bread", "eggs"]
shopping_list.append("butter")
print("After adding:", shopping_list)
shopping_list.remove("bread")
print("After removing:", shopping_list)

Excellent work! You now know how to work with lists and loops in Python.