So far, you've worked with individual variables that store single pieces of data. But in real programs, you often need to work with collections of related data—like a list of student names, a collection of test scores, or a series of tasks to complete. Python's lists are perfect for this.
Lists are one of Python's most versatile and commonly used data structures. They allow you to store multiple items in a single variable, access them by position, and manipulate them in powerful ways. Lists work seamlessly with loops, making them essential for processing collections of data. By the end of this lesson, you'll be able to create, modify, and work with lists effectively.
What You'll Learn
- How to create and initialize lists
- Accessing list elements by index
- Modifying lists (adding, removing, updating items)
- List slicing for accessing multiple elements
- Common list methods and operations
- Combining lists with loops
- List comprehensions for efficient list creation
- Best practices for working with lists
Creating Lists
A list is created by placing items inside square brackets [], separated by commas. Lists can contain any type of data—numbers, strings, booleans, or even other lists:
# Creating lists with different data types
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = [] # Empty list
# Lists can contain duplicates
scores = [85, 90, 85, 92, 88]
print(fruits)
print(numbers)
print(mixed)
You can also create lists using the list() function or by converting other data types:
# Creating lists in different ways
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
word_list = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
Accessing List Elements
Lists are ordered, meaning each item has a position (called an index). In Python, indexing starts at 0, so the first item is at index 0, the second at index 1, and so on:
# Accessing list elements by index
fruits = ["apple", "banana", "orange", "grape", "kiwi"]
print(fruits[0]) # First item: "apple"
print(fruits[1]) # Second item: "banana"
print(fruits[2]) # Third item: "orange"
# Negative indexing (counts from the end)
print(fruits[-1]) # Last item: "kiwi"
print(fruits[-2]) # Second to last: "grape"
You can also access a range of elements using slicing. Slicing uses the syntax list[start:stop]:
# List slicing
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4] - from index 2 to 4 (not including 5)
print(numbers[:4]) # [0, 1, 2, 3] - from start to index 3
print(numbers[5:]) # [5, 6, 7, 8, 9] - from index 5 to end
print(numbers[::2]) # [0, 2, 4, 6, 8] - every second item
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] - reversed
Modifying Lists
Lists are mutable, meaning you can change their contents after creation. You can modify individual elements, add new items, or remove existing ones:
# Modifying list elements
fruits = ["apple", "banana", "orange"]
fruits[1] = "grape" # Change second item
print(fruits) # ['apple', 'grape', 'orange']
# Adding items to a list
fruits.append("kiwi") # Add to the end
print(fruits) # ['apple', 'grape', 'orange', 'kiwi']
fruits.insert(1, "mango") # Insert at specific position
print(fruits) # ['apple', 'mango', 'grape', 'orange', 'kiwi']
# Removing items
fruits.remove("grape") # Remove by value
print(fruits) # ['apple', 'mango', 'orange', 'kiwi']
popped = fruits.pop() # Remove and return last item
print(popped) # "kiwi"
print(fruits) # ['apple', 'mango', 'orange']
fruits.pop(0) # Remove item at index 0
print(fruits) # ['mango', 'orange']
Common List Methods
Python provides many useful methods for working with lists. Here are the most important ones:
# Common list methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Finding information
print(len(numbers)) # Length: 8
print(numbers.count(1)) # Count occurrences: 2
print(numbers.index(4)) # Find index: 2
# Sorting and reversing
numbers.sort() # Sort in place
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
numbers.reverse() # Reverse in place
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# Creating sorted copy (doesn't modify original)
original = [3, 1, 4, 1, 5]
sorted_copy = sorted(original)
print(original) # [3, 1, 4, 1, 5] - unchanged
print(sorted_copy) # [1, 1, 3, 4, 5] - sorted
Combining Lists
You can combine lists using the + operator or extend one list with another:
# Combining lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Using + operator (creates new list)
combined = list1 + list2
print(combined) # [1, 2, 3, 4, 5, 6]
# Using extend (modifies original list)
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5, 6]
Lists and Loops
Lists work perfectly with loops. You can iterate over a list to process each item:
# Iterating over lists
fruits = ["apple", "banana", "orange", "grape"]
# Using for loop
for fruit in fruits:
print(f"I like {fruit}")
# Using for loop with index
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
# Using enumerate (better way to get index and value)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Here's a practical example combining lists with loops:
# Processing a list of scores
scores = [85, 92, 78, 96, 88, 91]
# Calculate average
total = 0
for score in scores:
total += score
average = total / len(scores)
print(f"Average score: {average:.2f}")
# Find highest score
highest = scores[0]
for score in scores:
if score > highest:
highest = score
print(f"Highest score: {highest}")
List Comprehensions
List comprehensions are a concise way to create lists. They're more Pythonic and often faster than using loops:
# List comprehension syntax: [expression for item in iterable]
# Create list of squares
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# Create list with condition
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Transform existing list
fruits = ["apple", "banana", "orange"]
uppercase = [fruit.upper() for fruit in fruits]
print(uppercase) # ['APPLE', 'BANANA', 'ORANGE']
List comprehensions are equivalent to writing a for loop, but more concise:
# These are equivalent:
# Using loop
squares = []
for x in range(1, 6):
squares.append(x**2)
# Using list comprehension
squares = [x**2 for x in range(1, 6)]
Practical Example: Student Grades
Let's combine everything we've learned in a practical example:
# Student grades management system
students = ["Alice", "Bob", "Charlie", "Diana"]
grades = [[85, 90, 88], [92, 87, 91], [78, 82, 80], [95, 93, 97]]
# Calculate average for each student
for i, student in enumerate(students):
student_grades = grades[i]
average = sum(student_grades) / len(student_grades)
print(f"{student}: {average:.2f}")
# Find class average
all_grades = []
for grade_list in grades:
all_grades.extend(grade_list)
class_average = sum(all_grades) / len(all_grades)
print(f"\nClass Average: {class_average:.2f}")
Try It Yourself
Practice working with lists using these exercises:
-
Shopping List Manager: Create a program that allows users to add items to a shopping list, remove items, and display the entire list.
-
Number Analyzer: Write a program that takes a list of numbers and finds the sum, average, maximum, and minimum values.
-
Word Processor: Create a program that takes a sentence, splits it into words, and then:
a. Prints each word on a separate line
b. Counts the total number of words
c. Finds the longest word -
Grade Calculator: Build a program that stores test scores in a list, calculates the average, and determines the letter grade based on the average.
These exercises will help you become comfortable with lists and their many operations.
Summary
In this lesson, you've learned how to work with lists—one of Python's most powerful data structures. You now understand how to create lists, access elements by index, modify lists by adding or removing items, use list methods for common operations, and combine lists with loops to process collections of data.
Lists are essential for storing and working with multiple related items. They're mutable, ordered, and can contain any type of data. Combined with loops, lists allow you to process large amounts of data efficiently.
Remember that list indices start at 0, and you can use negative indices to count from the end. Also, many list methods modify the list in place, so be aware of whether you're modifying the original list or creating a new one.
What's Next?
In the next lesson, we'll explore dictionaries—another powerful data structure that stores data as key-value pairs. Dictionaries are perfect for storing related information where you want to access values by name rather than position. You'll learn how dictionaries differ from lists and when to use each one.