Lesson 6.1: Creating and Accessing Lists
By the end of this lesson, you will be able to:
- Create lists using square brackets and the list() constructor
- Access individual elements using positive indexing
- Access elements from the end using negative indexing
- Find the number of items in a list using len()
- Check if an item exists in a list using the
inoperator
What is a List?
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)
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))
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)
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.
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)
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
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
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}")
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))
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!")
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)
Using in with Conditionals
allowed_users = ["alice", "bob", "charlie"] username = "bob" if username in allowed_users: print(f"Welcome, {username}!") else: print("Access denied.")
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"]
- What does
colors[2]return? - What does
colors[-1]return? - What is
len(colors)? - What does
"orange" in colorsreturn?
"green"(index 2 is the third element)"purple"(the last element)5(five items in the list)False("orange" is not in the list)
Key Takeaways
- Lists are created with square brackets:
[item1, item2, item3] - Indexing starts at 0: the first element is at index 0
- Negative indexing accesses elements from the end:
-1is the last element len()returns the number of items in a list- The
inkeyword checks whether an item exists in a list - Lists can contain any data type, including mixed types