Concept Explanation
Imagine you're going to the grocery store. You don't just carry each individual item in your hands; you put them all into a single shopping cart or a list. In Python, a List is exactly that—a single variable that can hold multiple pieces of information at once.
Lists are ordered, meaning the items have a specific place (index) in the list. They are also mutable, which is a fancy way of saying they can be changed after they are created. You can add items, remove them, or swap them out. They can even hold different types of data at the same time (integers, strings, or even other lists!).
Syntax or Core Structure
The Basics of Creation
Lists are defined by wrapping items in square brackets [] and separating them with commas.
# Creation
nums = [1, 2, 3]
mixed = ["Python", 3.10, True, [1, 2]] # Lists can hold anything!
# Accessing Items (Zero-indexed)
print(nums[0]) # 1 (The first item)
print(nums[-1]) # 3 (The last item - negative indexing)
Common List Methods
.append(item): Adds an item to the very end..insert(index, item): Squeezes an item into a specific spot..remove(item): Deletes the first occurrence of a specific value..pop(index): Removes and returns the item at that spot (defaults to the end)..sort(): Reorders the list alphabetically or numerically.
Code Example #1 (Basic)
Building and modifying a simple task list.
todo_list = ["Buy milk", "Clean room", "Code Python"]
# Add a new task
todo_list.append("Sleep")
# Someone did the second task
completed_item = todo_list.pop(1)
# Update an item
todo_list[0] = "Buy organic milk"
print(f"I finished: {completed_item}")
print(f"Remaining tasks: {todo_list}")
Code Example #2 (Intermediate)
Mastering Slicing. Slicing allows you to "cut out" a piece of a list without destroying the original. The syntax is list[start:stop:step].
original = [0, 10, 20, 30, 40, 50, 60]
# Get items from index 1 to 4 (5 is not included)
sub_list = original[1:5] # [10, 20, 30, 40]
# Get everything from the beginning to index 3
beginning = original[:4] # [0, 10, 20, 30]
# Get everything from index 4 to the end
ending = original[4:] # [40, 50, 60]
# Use a step to get every second item
steps = original[::2] # [0, 20, 40, 60]
# Reverse the list using slicing
reversed_list = original[::-1] # [60, 50, 40, 30, 20, 10, 0]
Real World Example
Imagine you are managing a user queue for a technical support chat. As new people join, they go to the end. When a support agent is free, they help the person at the front.
# 🎧 Support Queue Management
queue = ["User_Alice", "User_Bob", "User_Charlie"]
# A new user joins the queue
new_user = "User_David"
queue.append(new_user)
print(f"New Arrival: {new_user}. Queue length: {len(queue)}")
# Agent is free, process the first person (FIFO - First In First Out)
processing = queue.pop(0)
print(f"Now helping: {processing}")
# A VIP user joins and jumps to the second spot
queue.insert(1, "User_VIP_Emily")
print(f"Current waitlist: {queue}")
Common Mistakes
- IndexError: Trying to access
my_list[10]when the list only has 3 items. Always remember that Python starts counting at 0. - Confusing .append() and .extend():
append([1,2])adds the whole list as one single item.extend([1,2])adds each number individually. - Modifying while Looping: If you delete items from a list while you are using a
forloop to read it, you will likely skip items or cause a crash. It's better to create a new list or loop through a copy (my_list[:]).
Best Practices
- Use for Similar Items: While lists can hold different types of data, it's best practice to keep them "homogeneous" (all strings, or all numbers) so they are easier to process later.
- Prefer List Comprehension: When you need to create a new list based on an existing one, list comprehensions (which we'll cover soon!) are much faster and more "Pythonic" than manual loops.
Practice Exercises
- The Guest List: Create a list of 5 celebrities. Add one more to the end. Remove the 3rd person from the list. Print the final list sorted alphabetically.
- Number Cruncher: Create a list of numbers from 1 to 10. Extract a "slice" that contains only the numbers 4, 5, 6, and 7.
- The Swapper: Write a script that takes a list of two items and swaps their positions using their indices.