So far, you may have used variables to store single values like a number or a string. But what if you need to store a collection of values, like a list of grocery items or a series of temperatures? For this, Python provides a powerful and flexible data structure called a list.
📋 Creating and Accessing Lists
A list is an ordered collection of items. You create a list by enclosing a comma-separated sequence of values in square brackets []
. For example: my_numbers = [10, 20, 30, 40]
. Each item in the list, called an element, has a position or index, starting from 0. To access an individual element, you use its index in square brackets: my_numbers[0]
would give you `10`, and my_numbers[2]
would give you `30`.
🔄 Looping Through a List
One of the most common things you’ll do with a list is iterate over its elements. A for
loop is perfect for this. You can loop through each value directly, which is clean and simple: for number in my_numbers:
print(number)
. Alternatively, you can loop through the indices of the list using the len()
and range()
functions. This is useful when you need to know the position of each element.
✏️ Modifying a List
Lists are mutable, which means you can change them after they’ve been created. You can change an element by assigning a new value to a specific index: my_numbers[1] = 25
. You can also add new elements to the end of a list using the append()
method, like my_numbers.append(50)
. Or you can insert an element at a specific position with the insert()
method. These abilities make lists incredibly dynamic and useful for storing data that changes over time.
Lists are one of Python’s most fundamental data structures. Getting comfortable with creating, accessing, and modifying them is a key skill for any Python programmer.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python