Lists and List Operations
Overview
Lists are ordered, changeable collections of data that can hold multiple items of any type. You'll practice creating lists, accessing elements, slicing, and modifying them with methods like append(), remove(), and sort() to manipulate data efficiently.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Creating lists: Learn how to create lists with different types of data.
- List methods: Understand how to add, remove, and modify items in lists.
- Common operations: Discover useful operations like sorting and finding items.
- List properties: Understand that lists are ordered, changeable, and allow duplicates.
Why This Matters
Lists are one of the most commonly used data structures in Python. They're perfect for storing collections of items where order matters and you need to be able to add, remove, or change items. Whether you're managing a shopping cart, tracking scores, or storing user data, lists are essential tools for organizing information!
Step 1: Creating Lists
A list is created by placing items inside square brackets [], separated by commas. Lists can contain any type of data - numbers, strings, or even other lists!
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "orange"]
# List with mixed types
mixed = [1, "hello", 3.14, True]
# Empty list
empty = []
Use Square Brackets
Lists are created using square brackets []. This tells Python you're creating a list.
Separate with Commas
Items in a list are separated by commas. You can have as many items as you need.
Any Data Type
Lists can contain any type of data - numbers, strings, booleans, or even other lists. You can mix different types in the same list!
Key Concept: Lists are ordered, which means items stay in the order you put them. Lists are also changeable (mutable), which means you can add, remove, or modify items after creating the list. Lists also allow duplicates - you can have the same item appear multiple times!
Mini Practice #1: Creating Lists
Try It YourselfTry creating different types of lists:
What happened? You created lists using square brackets! Notice how each list keeps its items in order - the colors stay in the order you wrote them. Lists are flexible - you can create lists with any items you want, or even start with an empty list and add items later!
Step 2: Adding Items to Lists
You can add items to a list using the append() method, which adds an item to the end of the list:
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'orange']
How append() Works
The append() method adds a single item to the end of the list. It modifies the list directly - you don't need to assign the result back to the variable. The item is always added at the end, maintaining the order of existing items.
Step 3: Removing Items from Lists
You can remove items using remove() or pop():
fruits = ["apple", "banana", "orange"]
# Remove by value
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange']
# Remove by index (removes and returns the item)
last_fruit = fruits.pop()
print(last_fruit) # Output: 'orange'
print(fruits) # Output: ['apple']
remove() Method
remove() removes the first item that matches the value you specify. If the item appears multiple times, only the first occurrence is removed.
pop() Method
pop() removes and returns the item at a specific index. If you don't specify an index, it removes the last item. This is useful when you need both to remove an item and use its value.
Mini Practice #2: Adding and Removing Items
Try It YourselfTry adding and removing items from a list:
What happened? You used append() to add items to the end of the list, and remove() to remove a specific item. Notice how the list changes each time - lists are mutable, meaning you can modify them after creating them. The order is maintained - new items are added at the end!
Step 4: Other Useful List Methods
Python provides many useful methods for working with lists:
numbers = [3, 1, 4, 1, 5]
# Sort the list
numbers.sort()
print(numbers) # Output: [1, 1, 3, 4, 5]
# Reverse the list
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 1, 1]
# Count occurrences
count = numbers.count(1)
print(count) # Output: 2
# Find index
index = numbers.index(3)
print(index) # Output: 2
sort()
Sorts the list in ascending order. Modifies the list directly.
reverse()
Reverses the order of items in the list.
count()
Returns how many times a value appears in the list.
index()
Returns the index of the first occurrence of a value.
Step 5: Getting List Information
You can get information about lists using built-in functions:
fruits = ["apple", "banana", "orange"]
# Get length
length = len(fruits)
print(length) # Output: 3
# Check if item exists
has_apple = "apple" in fruits
print(has_apple) # Output: True
Remember: len() tells you how many items are in the list. The in keyword checks if an item exists in the list. These are very useful for checking list contents before performing operations!
End-of-Lesson Exercises
Exercise 1: Create and Modify a List
Create a list called grades with three numbers: 85, 90, 78. Add 92 to the list using append(), then remove 78 using remove(). Print the final list.
Use append() to add and remove() to remove items.
Exercise 2: Sort and Count
Create a list called numbers with values [5, 2, 8, 2, 1]. Sort the list, then count how many times 2 appears. Print both the sorted list and the count.
Use sort() to sort and count() to count occurrences.