Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 7

Working with Python Lists

Recommended resources

Welcome to the next step in your Python journey! In our last lesson, you learned how to create functions to package and reuse blocks of code. This is a fundamental skill for building organized programs. We created functions like create_welcome_message that worked with individual pieces of data, such as a single name or ticket ID.

However, real-world applications rarely deal with just one item at a time. Your support chatbot will need to handle a sequence of messages in a conversation, a list of open support tickets, or a collection of knowledge base articles. How can you store and manage these ordered collections of data?

This lesson introduces Python lists, a versatile and powerful data structure for exactly this purpose. You will learn how to create lists, and then how to perform the four core operations that make them so useful: storing, retrieving, updating, and iterating over items. Mastering lists is essential for handling the structured data your chatbot will depend on.

A New Way to Store Data: The List

So far, we've used variables to hold single values, like name = "Alice" or ticket_id = 12345. A list is a special kind of variable that can hold an ordered sequence of multiple values. Think of it as a container where you can line up items one after another.

In Python, we create a list by enclosing a comma-separated sequence of items in square brackets [].

# A list of ticket IDs (integers)
open_tickets = [76, 102, 105, 119]

# A list of user roles (strings)
user_roles = ["guest", "member", "admin"]

# A list can even be empty, which is useful when you want to add items later
conversation_history = [] 

The items in a list can be of any type, and you can even mix types, though it's most common to have lists where all items are of the same type.

To get a foundational understanding of what lists are and their basic properties, please read the first two sections of the "Python for Everybody" chapter on lists.

PY4E - Python for Everybody

This reading introduces the core concepts of what a list is and its most important property: mutability.

Read the first two sections, "A list is a sequence" and "Lists are mutable". Focus on understanding how lists are created with [] and the key difference between lists and strings: you can change the items inside a list.


Retrieving and Updating List Items

Once you have items in a list, you need a way to get them out (retrieve) and change them (update). This is done using an index—a number that specifies an item's position in the list.

A crucial concept in Python (and many other programming languages) is zero-based indexing. This means the first item is at index 0, the second at index 1, and so on.

#      index:  0         1        2
user_roles = ["guest", "member", "admin"]

# Retrieve the first item
first_role = user_roles[0]  # This will be "guest"
print(first_role)

# Update the second item
user_roles[1] = "subscriber" 
print(user_roles) # Output: ['guest', 'subscriber', 'admin']

You can also access items from the end of the list using negative indices. Index -1 refers to the last item, -2 to the second-to-last, and so on. This is incredibly handy for getting the most recent item in a sequence, like the last message in a chat.

The following video provides an excellent visual demonstration of how to access and modify list items.

How to Use Lists in Python

This video from Programming with Mosh clearly demonstrates how to interact with list items using indices and slices.

Watch the section on accessing items. Pay close attention to how he uses positive and negative indices to access individual items and how he modifies an item at a specific index. Also, watch the explanation of slicing, which lets you extract a sub-list.


Growing and Shrinking Your List

Lists are dynamic. In your chatbot, new messages arrive and old tickets get closed. You'll constantly be adding and removing items. This is done with list methods. Remember from the previous lesson how we used dot notation for string methods like .capitalize()? Lists have their own methods.

Here are the most common ones for adding and removing items:

  • .append(item): Adds an item to the very end of the list. This is perfect for adding a new message to a conversation_history list.
  • .insert(index, item): Adds an item at a specific position, shifting everything else down.
  • .pop(index): Removes the item at a specific index. If you don't provide an index, it removes the last item. It also returns the item it removed, which can be useful.
  • .remove(value): Searches for the first item with a specific value and removes it.

The video below walks through these essential methods.

How to Use Lists in Python

This part of the video covers the primary methods for adding and removing items from a list.

Watch the segment on adding and removing items. Focus on the difference between .append() for adding to the end and .insert() for adding at a specific spot. For removing, notice how .pop() uses an index while .remove() uses the actual value of the item.

Let's see this in the context of our chatbot:

# A list of active support tickets
active_tickets = [101, 105, 230]
print(f"Initial tickets: {active_tickets}")

# A new high-priority ticket comes in, add it to the end
active_tickets.append(112)
print(f"After append: {active_tickets}") # Output: [101, 105, 230, 112]

# Ticket 105 has been resolved, let's remove it
active_tickets.remove(105)
print(f"After remove: {active_tickets}") # Output: [101, 230, 112]

Iterating Over a List

Finally, you'll often need to perform an action for every single item in a list. This is called iteration. You've already seen for loops with range(); using them with lists is even more direct and readable.

The for...in loop is the standard way to iterate through a list in Python:

customer_questions = [
    "How do I reset my password?",
    "What is the status of ticket #54321?",
    "Can I upgrade my plan?"
]

print("Processing incoming questions:")
for question in customer_questions:
    # In a real app, you might log the question or send it to an AI
    print(f"- {question}") 

Sometimes, you need both the index and the item during the loop. The enumerate() function is perfect for this. It gives you back a pair of (index, item) for each element.

How to Use Lists in Python

This clip demonstrates the most common and pythonic ways to loop over the items in a list.

Watch the section on looping over lists. He first shows a simple for loop, then introduces the enumerate() function for when you need both the index and the value.


Practice Exercise

Let's apply these concepts to manage a queue of support chat sessions for your chatbot project.

Create a new Python file named session_queue.py.

  1. Initialize the queue: Create a list named session_ids and put a few initial session IDs in it (e.g., [ "s-101", "s-102", "s-103" ]).

  2. A new user starts a chat: A new session, "s-104", begins. Use the appropriate list method to add this new ID to the end of the session_ids list.

  3. The first session is handled: The first session in the queue ("s-101") has been completed. Use a list method to remove it from the list. Hint: .pop() with an index is a good choice here.

  4. Display the current queue: Write a for loop that iterates over the final session_ids list. Inside the loop, use print() to display each session ID that is still in the queue.

Your final output should look something like this:

Current sessions in queue:
s-102
s-103
s-104

Here's a template to get you started. Try to fill in the commented sections.

# 1. Initialize the list
session_ids = ["s-101", "s-102", "s-103"]
print(f"Initial queue: {session_ids}")

# 2. A new session arrives
# Your code here to add "s-104" to the end of the list
print(f"Queue after new session: {session_ids}")

# 3. The first session is handled
# Your code here to remove the item at index 0
handled_session = # ... your code to remove and store the session ID
print(f"Handled session: {handled_session}")
print(f"Queue after handling session: {session_ids}")


# 4. Display the current queue
print("\nCurrent sessions in queue:")
# Your 'for' loop here to print each remaining session ID

Conclusion

In this lesson, you've gained a critical tool for any programmer: the Python list. You now have the ability to manage ordered collections of data, which is a massive step up from working with single variables.

Here are the key takeaways:

  • Lists store ordered collections of items inside square brackets [].
  • Lists are mutable, meaning you can change them after they are created.
  • You retrieve items using zero-based indexing (e.g., my_list[0]) and slices (e.g., my_list[1:4]).
  • You update lists using methods like .append() to add items and .remove() or .pop() to delete them.
  • You iterate over every item in a list using a simple for item in my_list: loop.

Lists are perfect for sequences where the order matters, like the steps in a process or the messages in a conversation. But what happens when the order doesn't matter as much as the label? For instance, how would you store a user's profile, with fields for name, email, and user_id? For that, we need a way to connect keys to values. In the next lesson, we will explore Python dictionaries, which are designed for precisely this kind of key-value data.