Learn Without Walls
← Module 6 Home Lesson 1 of 4 Lesson 2 →

Lesson 6.1: Creating and Accessing Lists

By the end of this lesson, you will be able to:

What is a List?

List: A list is an ordered, mutable (changeable) collection of items in Python. Lists can hold items of any data type and can contain duplicate values.

So far, you have worked with individual variables that each store a single value. But what if you need to store a collection of related items -- like a list of student names, a series of test scores, or a set of temperatures? That is exactly what Python lists are designed for.

Lists are one of the four built-in collection data types in Python (alongside tuples, sets, and dictionaries). They are by far the most commonly used.

Real-World Analogy

Think of a list like a numbered shopping list. Each item has a position (1st, 2nd, 3rd...), you can add items, remove items, or change items. Python lists work the same way, except the numbering starts at 0 instead of 1.

Creating Lists

You create a list by placing items inside square brackets [], separated by commas.

Basic List Creation

# A list of strings
fruits = ["apple", "banana", "cherry"]
print(fruits)

# A list of numbers
scores = [95, 87, 92, 78, 100]
print(scores)

# A list with mixed data types
mixed = ["Alice", 25, True, 3.14]
print(mixed)
['apple', 'banana', 'cherry'] [95, 87, 92, 78, 100] ['Alice', 25, True, 3.14]

Empty Lists

You can create an empty list and add items to it later.

# Two ways to create an empty list
empty1 = []
empty2 = list()

print(empty1)
print(empty2)
print(type(empty1))
[] [] <class 'list'>

Using the list() Constructor

You can also create a list from other sequences using the list() function.

# Convert a string to a list of characters
letters = list("hello")
print(letters)

# Convert a range to a list
numbers = list(range(1, 6))
print(numbers)
['h', 'e', 'l', 'l', 'o'] [1, 2, 3, 4, 5]

Try It Yourself

Create a list called colors with at least 4 of your favorite colors. Print the list and its type.

Accessing Elements with Indexing

Every item in a list has a position number called an index. In Python, indexing starts at 0, not 1.

Index: The position number of an element in a list. The first element is at index 0, the second at index 1, and so on.
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
#          0          1          2         3          4

print(fruits[0])   # First element
print(fruits[1])   # Second element
print(fruits[4])   # Fifth element (last)
apple banana elderberry

Common Mistake: Index Out of Range

If you try to access an index that does not exist, Python raises an IndexError.

fruits = ["apple", "banana", "cherry"]

# This will cause an error!
print(fruits[3])   # IndexError: list index out of range
IndexError: list index out of range

Remember: for a list with 3 items, valid indexes are 0, 1, and 2 (not 3).

Negative Indexing

Python allows you to use negative indexes to access elements from the end of the list. The last element is at index -1, the second-to-last is at -2, and so on.

fruits = ["apple", "banana", "cherry", "date", "elderberry"]
#          -5         -4         -3        -2         -1

print(fruits[-1])   # Last element
print(fruits[-2])   # Second to last
print(fruits[-5])   # First element
elderberry date apple

When is Negative Indexing Useful?

Negative indexing is especially handy when you want to access the last element of a list without knowing how long the list is:

# Get the most recent score, no matter how many there are
scores = [88, 92, 75, 95, 89]
latest_score = scores[-1]
print(f"Latest score: {latest_score}")
Latest score: 89

Finding the Length of a List

Use the built-in len() function to find out how many items are in a list.

fruits = ["apple", "banana", "cherry"]
print(len(fruits))

# Useful for getting the last valid index
last_index = len(fruits) - 1
print(f"Last index: {last_index}")
print(f"Last item: {fruits[last_index]}")

# Empty list has length 0
empty = []
print(len(empty))
3 Last index: 2 Last item: cherry 0

Combining len() with Conditionals

shopping = ["milk", "eggs", "bread"]

if len(shopping) > 0:
    print(f"You have {len(shopping)} items to buy.")
else:
    print("Your shopping list is empty!")
You have 3 items to buy.

Checking Membership with in

Use the in keyword to check whether an item exists in a list. It returns True or False.

fruits = ["apple", "banana", "cherry"]

print("banana" in fruits)
print("grape" in fruits)

# Using 'not in'
print("grape" not in fruits)
True False True

Using in with Conditionals

allowed_users = ["alice", "bob", "charlie"]
username = "bob"

if username in allowed_users:
    print(f"Welcome, {username}!")
else:
    print("Access denied.")
Welcome, bob!

Try It Yourself

Create a list of 5 animals. Then write code that asks whether "cat" is in your list and prints an appropriate message.

Check Your Understanding

Given this list: colors = ["red", "blue", "green", "yellow", "purple"]

  1. What does colors[2] return?
  2. What does colors[-1] return?
  3. What is len(colors)?
  4. What does "orange" in colors return?
  1. "green" (index 2 is the third element)
  2. "purple" (the last element)
  3. 5 (five items in the list)
  4. False ("orange" is not in the list)

Key Takeaways