Python Lists
Lists allow you to store multiple items in a single variable, making it easy to group related data and perform operations on them. This time, we’ll learn how to create and modify lists, access elements, and use common methods.
Table of Contents
What is a List?
A list in Python is a collection of items (called ‘elements’) that are ordered, changeable (we say, ‘mutable’), and allow duplicate values.
Lists are defined using square brackets ([]
), with elements separated by commas.
Creating a List:
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
# A mixed list
mixed = [1, "apple", True, 3.14]
Empty List:
You can create an empty list and add elements to it later:
empty_list = []
Lists Are Ordered:
The order of elements in a list is maintained, meaning the first item in the list stays there unless you modify the list. Lists are great for storing ordered data like sequences.
Accessing List Elements
You can access elements in a list using indexing. The first item in a list has index 0
, the second has index 1
, and so on. You can also use negative indexing to access elements from the end of the list, where -1
refers to the last element.
Examples:
fruits = ["apple", "banana", "cherry"]
# Accessing the first element
print(fruits[0]) # Output: apple
# Accessing the last element
print(fruits[-1]) # Output: cherry
Slicing a List:
You can use slicing to access a range of elements. The slice syntax is list[start:end]
, where start
is the index where the slice begins, and end
is where it ends (but the end
index is not included).
# Slicing the first two elements
print(fruits[0:2]) # Output: ['apple', 'banana']
# Slicing from the second element to the end
print(fruits[1:]) # Output: ['banana', 'cherry']
Modifying Lists
One of the key features of lists is that they are mutable, meaning you can change, add, or remove elements after the list is created.
Changing List Elements:
You can change an individual element by assigning a new value to its index.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
Adding Elements to a List:
append()
: Adds an element to the end of the list.
fruits.append("orange")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'orange']
insert()
: Inserts an element at a specific position in the list.
fruits.insert(1, "kiwi")
print(fruits) # Output: ['apple', 'kiwi', 'blueberry', 'cherry']
Removing Elements from a List:
remove()
: Removes the first occurrence of an element.
fruits.remove("blueberry")
print(fruits) # Output: ['apple', 'kiwi', 'cherry']
pop()
: Removes an element by its index (if no index is specified, it removes the last element).
fruits.pop(1)
print(fruits) # Output: ['apple', 'cherry']
clear()
: Removes all elements from the list, making it empty.
fruits.clear()
print(fruits) # Output: []
List Methods
Python provides a variety of built-in methods to perform common operations on lists. Below are some of the most useful ones:
Method | Description | Example |
---|---|---|
append(item) | Adds an item to the end of the list | numbers.append(6) |
insert(index, item) | Inserts an item at a specific position | fruits.insert(1, "orange") |
remove(item) | Removes the first occurrence of an item | fruits.remove("apple") |
pop(index) | Removes the item at the specified position | fruits.pop(2) |
clear() | Removes all elements from the list | fruits.clear() |
index(item) | Returns the index of the first occurrence of an item | fruits.index("cherry") |
count(item) | Returns the number of occurrences of an item | fruits.count("apple") |
sort() | Sorts the list in ascending order | numbers.sort() |
reverse() | Reverses the order of the list | numbers.reverse() |
Iterating Over a List
You can use a for loop to iterate over the elements of a list.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This will print each fruit on a new line:
apple
banana
cherry
Using enumerate()
to Get the Index and Value:
If you need both the index and the value of the elements during iteration, use the enumerate()
function.
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
This will output:
0: apple
1: banana
2: cherry
Checking If an Item is in a List
You can use the in
keyword to check if an element exists in a list.
Example:
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Banana is in the list!")
If “banana” is found in the list, it prints the message.
Copying a List
Assigning a list to a new variable using =
doesn’t create a copy of the list — it creates a reference to the same list. If you want to create an actual copy of the list, use the copy()
method.
Example:
fruits = ["apple", "banana", "cherry"]
# Incorrect way (creates a reference)
new_fruits = fruits
# Correct way (creates a copy)
new_fruits = fruits.copy()
Now, modifying new_fruits
won’t affect the original fruits
list.
List Comprehension
List ‘comprehension’ is a concise way to create lists in Python. It’s a compact way to generate lists using a for
loop inside square brackets.
Example:
# Create a list of squares using list comprehension
squares = [x**2 for x in range(6)]
print(squares) # Output: [0, 1, 4, 9, 16, 25]
List comprehension can also include conditions:
# Create a list of even numbers from 0 to 10
evens = [x for x in range(11) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8, 10]
Example: Building a Simple Program
Let’s build a simple program that asks the user for a list of numbers and then calculates the average.
Average Calculator Program:
# Get input from the user and split it into a list of numbers
numbers = input("Enter numbers separated by spaces: ").split()
# Convert the strings in the list to integers
numbers = [int(num) for num in numbers]
# Calculate the average
average = sum(numbers) / len(numbers)
print(f"The average of the numbers is: {average}")
How it works:
- The program takes input from the user as a string and splits it into a list of numbers.
- List comprehension is used to convert each element from a string to an integer.
- The
sum()
andlen()
functions are used to calculate the average.
Key Concepts Recap
- A list is a collection of items that are ordered and mutable.
- You can access, modify, and slice lists using indexes.
- Python provides several useful list methods such as
append()
,insert()
,remove()
,pop()
, andsort()
. - Use for loops and list comprehensions to iterate through lists and create new lists.
- You can copy lists using the
copy()
method
Next time we’ll look at arranging data with Python dictionaries!
FAQ
Q1: What’s the difference between using append() and insert() to add items to a list?
A1:
append()
adds an item to the end of the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ["apple", "banana", "cherry"]
insert()
allows you to add an item at a specific index in the list.
fruits.insert(1, "orange")
print(fruits) # Output: ["apple", "orange", "banana"]
Use append()
when you always want to add to the end of the list, and use insert()
when you need to control exactly where the new item goes.
Q2: Why do I get an error when I try to access an index that doesn’t exist in the list?
A2: This happens because lists are indexed and Python throws an IndexError when you try to access an index that is out of range. For example:
fruits = ["apple", "banana"]
print(fruits[2]) # IndexError: list index out of range
To prevent this error, always make sure the index you’re trying to access is within the bounds of the list:
if index < len(fruits):
print(fruits[index])
Q3: How can I add multiple elements to a list at once?
A3: You can use the extend()
method to add multiple elements from another list or iterable to the end of a list. It’s different from append()
because append()
only adds a single item, while extend()
adds each element from the iterable.
Example:
fruits = ["apple", "banana"]
new_fruits = ["cherry", "orange"]
fruits.extend(new_fruits)
print(fruits) # Output: ["apple", "banana", "cherry", "orange"]
Q4: What’s the difference between remove()
, pop()
, and del
for removing elements?
A4:
remove(item)
: Removes the first occurrence of the specified item from the list. If the item doesn’t exist, it raises aValueError
.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) # Output: ["apple", "cherry"]
pop(index)
: Removes the item at the specified index and returns it. If no index is specified, it removes the last item.
fruits = ["apple", "banana", "cherry"]
popped = fruits.pop(1)
print(popped) # Output: "banana"
del list[index]
: Deletes an item by its index. It doesn’t return the value, and you can also use it to delete slices of a list.
fruits = ["apple", "banana", "cherry"]
del fruits[0]
print(fruits) # Output: ["banana", "cherry"]
Q5: Why is assigning a list to another variable not creating a new copy of the list?
A5: When you assign a list to another variable (e.g., new_list = old_list
), Python doesn’t create a copy. Instead, it creates a reference to the same list. This means changes made to one list will affect the other.
Example:
list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1) # Output: [1, 2, 3, 4]
To create a copy of the list, use the copy()
method:
list2 = list1.copy()
list2.append(4)
print(list1) # Output: [1, 2, 3]
print(list2) # Output: [1, 2, 3, 4]
Q6: How do I reverse the order of a list without sorting it?
A6: You can reverse the order of elements in a list using the reverse()
method. This changes the list in place.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) # Output: ["cherry", "banana", "apple"]
If you want to create a reversed copy of the list without modifying the original, you can use slicing:
reversed_fruits = fruits[::-1]
Q7: Can I have a list of lists? How do I access elements in nested lists?
A7: Yes, you can have lists inside lists, called nested lists. You can access elements inside a nested list by using multiple indices.
Example:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing the first list
print(nested_list[0]) # Output: [1, 2, 3]
# Accessing the first element of the first list
print(nested_list[0][0]) # Output: 1
In this case, nested_list[0]
gives you the first list, and nested_list[0][0]
gives you the first element of that list.
Q8: How do I count how many times an item appears in a list?
A8: You can use the count()
method to count how many times an item appears in a list.
Example:
fruits = ["apple", "banana", "apple", "cherry"]
count_apples = fruits.count("apple")
print(count_apples) # Output: 2
Q9: How can I sort a list of numbers or strings in reverse order?
A9: You can use the sort()
method with the reverse=True
argument to sort the list in descending order.
Example:
numbers = [5, 2, 9, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 5, 2, 1]
Alternatively, you can use the sorted()
function to return a sorted copy of the list without modifying the original list:
sorted_numbers = sorted(numbers, reverse=True)
Q10: Can I use list comprehension with conditions?
A10: Yes! You can add conditions to a list comprehension to filter elements when creating a new list.
Example of list comprehension with a condition:
# Create a list of even numbers between 1 and 10
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # Output: [2, 4, 6, 8, 10]
In this case, only numbers that meet the condition x % 2 == 0
(i.e., even numbers) are added to the new list.
Q11: Why does slicing a list return a new list instead of modifying the original list?
A11: Slicing a list creates a new list containing the sliced elements. It doesn’t modify the original list because slicing in Python always creates a copy of the selected portion of the list.
Example:
numbers = [1, 2, 3, 4, 5]
sliced = numbers[1:4]
print(sliced) # Output: [2, 3, 4]
The numbers
list remains unchanged, and the sliced
list contains the extracted elements.
Q12: How do I iterate over a list and modify it at the same time?
A12: Modifying a list while iterating over it can lead to unexpected results, especially when adding or removing elements. A safe approach is to iterate over a copy of the list or use list comprehension to generate a modified list.
Example (using list comprehension):
numbers = [1, 2, 3, 4, 5]
# Create a new list with all numbers doubled
doubled = [x * 2 for x in numbers]
print(doubled) # Output: [2, 4, 6, 8, 10]
Alternatively, iterate over a copy:
for num in numbers[:]: # Iterate over a copy
if num % 2 == 0:
numbers.remove(num)
print(numbers) # Output: [1, 3, 5]