Chapter 7: Python Lists – Creating, Accessing and Modifying Lists
7.1 Introduction
Python programs often need to store multiple values together.
For example, suppose we want to store the names of five students:
student1 = "Aman" student2 = "Ravi" student3 = "Neha" student4 = "Priya" student5 = "Karan"
This approach works, but it becomes difficult when we have hundreds or thousands of values.
Python provides a powerful data structure called a list that allows us to store multiple items in a single variable.
Example:
students = ["Aman", "Ravi", "Neha", "Priya", "Karan"]
Lists are one of the most commonly used data structures in Python.
7.2 What is a List?
A list is an ordered collection of items.
A list can contain:
Numbers
Strings
Boolean values
Other lists
Different types of values
Example:
numbers = [10, 20, 30, 40, 50]
Another example:
student = ["Aman", 20, "Delhi", 85.5]
Python lists are:
Ordered
Mutable
Allow duplicate values
Able to contain different data types
7.3 Creating a List
Lists are created using square brackets [].
Example:
fruits = ["Apple", "Banana", "Mango"]
A list can also be empty:
items = []
You can add items later.
7.4 Creating Lists with Numbers
Example:
numbers = [10, 20, 30, 40, 50] print(numbers)
Output:
[10, 20, 30, 40, 50]
7.5 Creating a List of Strings
subjects = ["Maths", "Science", "English", "Computer"]
You can display the complete list:
print(subjects)
Output:
['Maths', 'Science', 'English', 'Computer']
7.6 Empty Lists
An empty list contains no elements.
students = [] print(students)
Output:
[]
Empty lists are useful when you want to create a collection and add items later.
7.7 List Indexing
Each item in a list has a position called an index.
Python list indexing starts from 0.
Example:
fruits = ["Apple", "Banana", "Mango", "Orange"]
The indexes are:
| Index | Value |
|---|---|
| 0 | Apple |
| 1 | Banana |
| 2 | Mango |
| 3 | Orange |
7.8 Accessing List Items
Use the index to access an item.
fruits = ["Apple", "Banana", "Mango"] print(fruits[0]) print(fruits[1]) print(fruits[2])
Output:
Apple Banana Mango
7.9 Negative Indexing
Python also supports negative indexes.
The last item has index -1.
Example:
fruits = ["Apple", "Banana", "Mango", "Orange"] print(fruits[-1]) print(fruits[-2])
Output:
Orange Mango
Negative indexing is useful when you want to access items from the end of a list.
7.10 Changing List Items
Lists are mutable, which means their items can be changed after the list is created.
Example:
fruits = ["Apple", "Banana", "Mango"] fruits[1] = "Orange" print(fruits)
Output:
['Apple', 'Orange', 'Mango']
The second item was changed from Banana to Orange.
7.11 Adding Items with append()
The append() method adds an item to the end of a list.
Example:
fruits = ["Apple", "Banana"] fruits.append("Mango") print(fruits)
Output:
['Apple', 'Banana', 'Mango']
7.12 Adding Multiple Items with extend()
The extend() method adds items from another iterable.
Example:
fruits = ["Apple", "Banana"] fruits.extend(["Mango", "Orange"]) print(fruits)
Output:
['Apple', 'Banana', 'Mango', 'Orange']
7.13 Difference Between append() and extend()
Consider:
fruits = ["Apple", "Banana"] fruits.append(["Mango", "Orange"]) print(fruits)
Output:
['Apple', 'Banana', ['Mango', 'Orange']]
The entire list was added as one item.
With extend():
fruits = ["Apple", "Banana"] fruits.extend(["Mango", "Orange"]) print(fruits)
Output:
['Apple', 'Banana', 'Mango', 'Orange']
So:
append() adds one object as an item.
extend() adds the elements from another iterable.
7.14 Adding an Item at a Specific Position
The insert() method adds an item at a specified index.
Example:
fruits = ["Apple", "Mango"] fruits.insert(1, "Banana") print(fruits)
Output:
['Apple', 'Banana', 'Mango']
7.15 Removing an Item with remove()
The remove() method removes the first matching value.
Example:
fruits = ["Apple", "Banana", "Mango"] fruits.remove("Banana") print(fruits)
Output:
['Apple', 'Mango']
If the specified value does not exist, Python raises a ValueError.
7.16 Removing an Item with pop()
The pop() method removes an item by index and returns the removed value.
Example:
fruits = ["Apple", "Banana", "Mango"] removed = fruits.pop(1) print("Removed:", removed) print(fruits)
Output:
Removed: Banana ['Apple', 'Mango']
If no index is provided, pop() removes the last item.
fruits = ["Apple", "Banana", "Mango"] fruits.pop() print(fruits)
Output:
['Apple', 'Banana']
7.17 Deleting an Item with del
The del statement can delete an item by index.
fruits = ["Apple", "Banana", "Mango"] del fruits[1] print(fruits)
Output:
['Apple', 'Mango']
You can also delete a range of items:
numbers = [1, 2, 3, 4, 5] del numbers[1:3] print(numbers)
Output:
[1, 4, 5]
7.18 Clearing a List
The clear() method removes all items from a list.
fruits = ["Apple", "Banana", "Mango"] fruits.clear() print(fruits)
Output:
[]
The list still exists, but it contains no items.
7.19 Finding the Length of a List
The len() function returns the number of items in a list.
fruits = ["Apple", "Banana", "Mango"] print(len(fruits))
Output:
3
7.20 Checking Whether an Item Exists
The in operator can check whether a value exists in a list.
fruits = ["Apple", "Banana", "Mango"] if "Mango" in fruits: print("Mango is available")
Output:
Mango is available
You can also use not in.
if "Orange" not in fruits: print("Orange is not available")
7.21 Looping Through a List
A for loop can be used to process every item.
fruits = ["Apple", "Banana", "Mango"] for fruit in fruits: print(fruit)
Output:
Apple Banana Mango
This connects lists with the loops learned in the previous chapter.
7.22 Using while with a List
You can also use a while loop.
fruits = ["Apple", "Banana", "Mango"] i = 0 while i < len(fruits): print(fruits[i]) i += 1
Output:
Apple Banana Mango
7.23 List Slicing
Slicing allows you to extract part of a list.
Syntax:
list[start:stop]
Example:
numbers = [10, 20, 30, 40, 50] print(numbers[1:4])
Output:
[20, 30, 40]
The stop index is not included.
7.24 Slicing from the Beginning
You can omit the starting index.
numbers = [10, 20, 30, 40, 50] print(numbers[:3])
Output:
[10, 20, 30]
7.25 Slicing to the End
You can omit the ending index.
numbers = [10, 20, 30, 40, 50] print(numbers[2:])
Output:
[30, 40, 50]
7.26 Slicing with a Step
The syntax can include a step:
list[start:stop:step]
Example:
numbers = [1, 2, 3, 4, 5, 6] print(numbers[::2])
Output:
[1, 3, 5]
7.27 Reversing a List with Slicing
A list can be reversed using slicing.
numbers = [1, 2, 3, 4, 5] print(numbers[::-1])
Output:
[5, 4, 3, 2, 1]
The reverse() method can also be used when you want to modify the original list.
7.28 Sorting a List
The sort() method sorts a list in ascending order.
numbers = [50, 10, 40, 20, 30] numbers.sort() print(numbers)
Output:
[10, 20, 30, 40, 50]
7.29 Sorting in Descending Order
Use reverse=True.
numbers = [50, 10, 40, 20, 30] numbers.sort(reverse=True) print(numbers)
Output:
[50, 40, 30, 20, 10]
7.30 sorted() Function
The sorted() function creates a new sorted list.
numbers = [30, 10, 20] new_numbers = sorted(numbers) print(new_numbers) print(numbers)
Output:
[10, 20, 30] [30, 10, 20]
Unlike sort(), sorted() does not modify the original list.
7.31 Reversing a List
The reverse() method reverses the existing list.
numbers = [1, 2, 3, 4, 5] numbers.reverse() print(numbers)
Output:
[5, 4, 3, 2, 1]
7.32 Finding the Minimum and Maximum
For numeric lists, Python provides min() and max().
numbers = [10, 50, 20, 40, 30] print("Minimum:", min(numbers)) print("Maximum:", max(numbers))
Output:
Minimum: 10 Maximum: 50
7.33 Calculating the Sum
The sum() function calculates the total of numeric values.
numbers = [10, 20, 30, 40] print(sum(numbers))
Output:
100
7.34 Counting an Item
The count() method tells you how many times a value appears.
numbers = [10, 20, 10, 30, 10] print(numbers.count(10))
Output:
3
7.35 Finding an Item with index()
The index() method returns the index of the first matching value.
fruits = ["Apple", "Banana", "Mango"] print(fruits.index("Banana"))
Output:
1
If the item does not exist, Python raises a ValueError.
7.36 Copying a List
You can make a copy using the copy() method.
numbers = [1, 2, 3] new_numbers = numbers.copy() print(new_numbers)
This creates a separate list.
7.37 Why Simple Assignment Is Different
Consider:
numbers = [1, 2, 3] new_numbers = numbers new_numbers.append(4) print(numbers)
Output:
[1, 2, 3, 4]
Both variables refer to the same list object.
Using copy() creates a separate list:
numbers = [1, 2, 3] new_numbers = numbers.copy() new_numbers.append(4) print(numbers) print(new_numbers)
Output:
[1, 2, 3] [1, 2, 3, 4]
7.38 Lists with Different Data Types
Python lists can contain different types of values.
data = ["Aman", 20, 85.5, True] print(data)
Output:
['Aman', 20, 85.5, True]
Although this is allowed, using a consistent data structure often makes programs easier to understand.
7.39 Nested Lists
A list can contain another list.
This is called a nested list.
Example:
students = [ ["Aman", 85], ["Ravi", 78], ["Neha", 92] ]
You can access nested values using multiple indexes.
print(students[0][0]) print(students[0][1])
Output:
Aman 85
7.40 Looping Through Nested Lists
students = [ ["Aman", 85], ["Ravi", 78], ["Neha", 92] ] for student in students: print("Name:", student[0]) print("Marks:", student[1])
Output:
Name: Aman Marks: 85 Name: Ravi Marks: 78 Name: Neha Marks: 92
7.41 List Comprehension
Python provides a concise way to create lists called list comprehension.
Example:
numbers = [1, 2, 3, 4, 5] squares = [number ** 2 for number in numbers] print(squares)
Output:
[1, 4, 9, 16, 25]
The general structure is:
[expression for item in iterable]
7.42 List Comprehension with a Condition
You can include a condition.
Example:
numbers = range(1, 11) even_numbers = [number for number in numbers if number % 2 == 0] print(even_numbers)
Output:
[2, 4, 6, 8, 10]
List comprehensions are useful, but normal loops may be clearer when the logic becomes complicated.
7.43 Converting Other Data to a List
The list() function can convert certain iterables into lists.
Example:
text = "Python" letters = list(text) print(letters)
Output:
['P', 'y', 't', 'h', 'o', 'n']
Another example:
numbers = list(range(1, 6)) print(numbers)
Output:
[1, 2, 3, 4, 5]
7.44 Taking List Input from the User
The input() function returns a string.
If you want a list of words, you can use split().
names = input("Enter names separated by spaces: ").split() print(names)
If the user enters:
Aman Ravi Neha
The output will be:
['Aman', 'Ravi', 'Neha']
7.45 Taking Numbers into a List
You can convert each input value to an integer.
numbers = input("Enter numbers separated by spaces: ").split() numbers = [int(number) for number in numbers] print(numbers)
If the user enters:
10 20 30 40
Output:
[10, 20, 30, 40]
7.46 Example: Student Marks Analyzer
marks = [78, 85, 92, 67, 74] print("Marks:", marks) print("Total:", sum(marks)) print("Highest:", max(marks)) print("Lowest:", min(marks)) print("Average:", sum(marks) / len(marks))
Output:
Marks: [78, 85, 92, 67, 74] Total: 396 Highest: 92 Lowest: 67 Average: 79.2
7.47 Example: Search for a Student
students = ["Aman", "Ravi", "Neha", "Priya"] name = input("Enter student name: ") if name in students: print("Student found") else: print("Student not found")
7.48 Example: Remove Duplicate Values
A simple way to remove duplicates is to use a set and then convert it back to a list.
numbers = [10, 20, 10, 30, 20, 40] unique_numbers = list(set(numbers)) print(unique_numbers)
A set does not preserve the original order in the same way a list does. If preserving order is important, a different approach should be used.
7.49 Example: Create a List of Squares
Using a loop:
squares = [] for number in range(1, 6): squares.append(number ** 2) print(squares)
Output:
[1, 4, 9, 16, 25]
Using list comprehension:
squares = [number ** 2 for number in range(1, 6)] print(squares)
Both approaches produce the same values.
7.50 Common List Mistakes
Mistake 1: Using an invalid index
numbers = [10, 20, 30] print(numbers[5])
This causes an IndexError because index 5 does not exist.
Mistake 2: Forgetting that indexing starts at zero
For:
numbers = [10, 20, 30]
The first item is:
numbers[0]
not:
numbers[1]
Mistake 3: Removing a value that does not exist
fruits = ["Apple", "Banana"] fruits.remove("Mango")
This causes a ValueError.
You can check first:
if "Mango" in fruits: fruits.remove("Mango")
7.51 Mini Project: Shopping List
shopping_list = [] while True: print("\n--- Shopping List ---") print("1. Add item") print("2. View items") print("3. Remove item") print("4. Exit") choice = input("Enter choice: ") if choice == "1": item = input("Enter item: ") shopping_list.append(item) print("Item added.") elif choice == "2": if shopping_list: print("\nYour Shopping List:") for index, item in enumerate(shopping_list, start=1): print(index, ".", item) else: print("Shopping list is empty.") elif choice == "3": item = input("Enter item to remove: ") if item in shopping_list: shopping_list.remove(item) print("Item removed.") else: print("Item not found.") elif choice == "4": print("Program ended.") break else: print("Invalid choice.")
This project demonstrates:
Lists
append()
remove()
in
for
while
enumerate()
Conditional statements
7.52 Mini Project: Student Marks Manager
students = [] number_of_students = int(input("How many students? ")) for i in range(number_of_students): name = input("Enter student name: ") marks = float(input("Enter marks: ")) students.append([name, marks]) print("\n--- Student Records ---") for student in students: print("Name:", student[0]) print("Marks:", student[1]) print("\nTotal students:", len(students))
This program stores multiple student records inside a nested list.
7.53 Chapter Summary
In this chapter, you learned:
What lists are
Creating lists
Empty lists
List indexing
Negative indexing
Modifying list items
append()
extend()
insert()
remove()
pop()
del
clear()
len()
in and not in
Looping through lists
List slicing
Sorting
Reversing
min()
max()
sum()
count()
index()
Copying lists
Nested lists
List comprehensions
Converting data to lists
Taking list input
Practical list programs
Lists are an essential Python data structure and are used extensively in real-world programs.
Quick Revision Questions
1. What is a list?
A list is an ordered, mutable collection of items.
2. Which brackets are used to create a list?
Square brackets [].
3. What is the index of the first list item?
0.
4. Which method adds an item to the end of a list?
append().
5. Which method adds multiple elements from another iterable?
extend().
6. Which method removes the first matching value?
remove().
7. Which method removes and returns an item by index?
pop().
8. Which function returns the number of items in a list?
len().
9. Can a list contain duplicate values?
Yes.
10. Can a list contain different data types?
Yes.
11. What is a nested list?
A list containing one or more other lists.
12. What is list comprehension?
A concise syntax for creating a new list from an iterable, optionally using a condition.
Practice Exercises
Exercise 1: Create a List
Create a list containing the names of five fruits and display the list.
Exercise 2: Access Items
Create a list of five numbers and display the first, third, and last items.
Exercise 3: Modify a List
Create a list of five subjects and replace one subject with another.
Exercise 4: Add Items
Create an empty list and use append() to add five student names.
Exercise 5: Remove Items
Create a list of fruits and remove one fruit using remove().
Exercise 6: Find Maximum
Create a list of numbers and find the largest number.
Exercise 7: Find Minimum
Create a list of numbers and find the smallest number.
Exercise 8: Calculate Average
Create a list of marks and calculate the average.
Exercise 9: Even Numbers
Create a list of numbers and generate a new list containing only even numbers.
Exercise 10: List Search
Ask the user for a name and check whether it exists in a list of student names.
Chapter Activity
Create a Student Marks Management System using lists.
The program should:
Store the names of students.
Store their marks.
Display all students.
Display the highest marks.
Display the lowest marks.
Calculate the average marks.
Search for a student by name.
Allow a student record to be removed.
Display the total number of students.
Try to combine:
Lists
Nested lists
Functions
Loops
Conditional statements
Next Chapter: Python Tuples – Creating, Accessing and Using Tuples