Working with Lists in Python
A list is like a shopping basket where you can store multiple items (like numbers, text, or even other lists). For example:
fruits = ["Apple", "Banana", "Cherry"] # A list of fruits
numbers = [1, 2, 3, 4] # A list of numbers
Creating a List in Python
In Python, a list is an ordered collection of items. To create a list, you can follow these steps:
- Use square brackets: Lists are created by enclosing elements in square brackets
[ ]
. - Separate items with commas: The items inside the list are separated by commas
,
. - Give the list a name: You can assign the list to a variable. For example,
fruits
could be the name of your list.
Example 1: Creating a simple list of colors:
# Create a list of colors
colors = ["Red", "Green", "Blue"]
print(colors) # Output: ["Red", "Green", "Blue"]
In this example, we created a list named colors
that contains three items: "Red",
"Green", and "Blue".
Example 2: Creating a list with different types of data (Mixed Data):
# A list with different types of data
mixed_list = ["Hello", 42, True, 3.14]
print(mixed_list) # Output: ["Hello", 42, True, 3.14]
Here, we created a list named mixed_list
that contains a string ("Hello"), an integer
(42), a boolean value (True), and a floating-point number (3.14). Python allows you to store
different types of data in a single list!
Accessing List Elements in Python
In Python, a list is an ordered collection of elements, where each element is assigned an index number. The index helps us access specific elements in the list.
Think of a list like a sequence of houses, where each house has a unique number (index). This number starts at 0 for the first item, and each subsequent item gets the next number.
- First item: Index 0 (Not 1!)
- Second item: Index 1
- Last item: Index -1 (Accessing from the end)
In Python, you can access list elements by specifying their index in square brackets []
.
Remember, the list indexing starts at 0:
Example:
animals = ["Cat", "Dog", "Elephant", "Giraffe"]
print(animals[0]) # Output: Cat (First item at index 0)
print(animals[2]) # Output: Elephant (Third item at index 2)
print(animals[-1]) # Output: Giraffe (Last item using negative indexing)
Here’s what happens in the example:
- animals[0] accesses the first item in the list, "Cat".
- animals[2] accesses the third item, "Elephant".
- animals[-1] accesses the last item in the list, "Giraffe".
⚠️ Common Mistake:
Attempting to access an index that doesn’t exist in the list will result in an error. For
example, if you try to access an index that is out of range (like animals[4]
in a
list with only 4 items), you’ll get an IndexError.
# This will cause an error if the list has less than 4 items!
print(animals[4])
List indexes are zero-based, meaning they start from 0. So, for a list of length 4, the valid indexes are 0, 1, 2, and 3. Trying to access index 4 is outside the valid range.
Changing Items in a List
Updating a list is like changing a TV channel. You can directly modify an element in the list by specifying its index.
# Original list
pets = ["Goldfish", "Parrot", "Hamster"]
# Change index 1 (Parrot → Dog)
pets[1] = "Dog"
print(pets) # Output: ["Goldfish", "Dog", "Hamster"]
In this example, the element at index 1 (which is "Parrot") is updated to "Dog". The list now looks like this: ["Goldfish", "Dog", "Hamster"].
Adding Items to a List
There are two common ways to add items to a list:
Method 1: append()
- Add to the End of the List
colors = ["Red", "Blue"]
colors.append("Green")
print(colors) # Output: ["Red", "Blue", "Green"]
The append()
method adds an item to the end of the list. Here, we add
"Green" to the existing list of colors.
Method 2: insert()
- Add at a Specific Position
# Insert "Yellow" at index 1
colors.insert(1, "Yellow")
print(colors) # Output: ["Red", "Yellow", "Blue", "Green"]
The insert()
method allows you to add an item at a specific index in the list. Here, we
insert "Yellow" at index 1, which shifts the other items accordingly.
Removing Items from a List
Method 1: remove()
- Remove by Value
fruits = ["Apple", "Banana", "Mango"]
fruits.remove("Banana") # Remove Banana
print(fruits) # Output: ["Apple", "Mango"]
The remove()
method removes the first occurrence of the specified item. In this example,
"Banana" is removed from the list, leaving ["Apple", "Mango"].
Method 2: pop()
- Remove by Position
# Remove and return the last item
last_fruit = fruits.pop()
print(last_fruit) # Output: Mango
print(fruits) # Output: ["Apple"]
The pop()
method removes the item at the specified index and returns it. If no index is
provided, it removes and returns the last item in the list. In this case, "Mango" is removed from
the list.
🚀 Practice Time!
Try this exercise step by step:
# Start with this list
groceries = ["Milk", "Bread", "Eggs"]
# 1. Add "Butter" to the end
groceries.append("Butter")
# 2. Change "Bread" to "Whole Wheat Bread"
groceries[1] = "Whole Wheat Bread"
# 3. Remove "Eggs"
groceries.remove("Eggs")
print(groceries) # Final Output: ["Milk", "Whole Wheat Bread", "Butter"]
This exercise helps you practice adding, changing, and removing items from a list step by step.
❓ Common Questions
Q: Can a list have duplicate values?
A: Yes! A list can contain the same value multiple times. For example, [1, 1, 2]
is a
valid list.
Q: How to check the length of a list?
A: You can use the built-in len()
function to check the length of a list (i.e., how
many items are in it). For example: print(len(fruits))