8.1. Lists
Table of Contents
Understanding Lists in Python
Lists are one of the most commonly used data collections in Python. They are ordered, changeable (mutable), and can hold a mix of different data types.
This chapter focuses specifically on how to create, use, and modify lists.
Creating Lists
A list is written with square brackets [], with items separated by commas.
numbers = [1, 2, 3, 4]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "hello", 3.14, True]
empty_list = []
You can also create a list using the list() function:
text = "hello"
characters = list(text) # ['h', 'e', 'l', 'l', 'o']Accessing List Items (Indexing)
List items are ordered. Each item has a position (index), starting from 0.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherryNegative indexes count from the end:
-1is the last item-2is the second-to-last item
print(fruits[-1]) # cherry
print(fruits[-2]) # bananaChanging Items in a List
Lists are mutable, so you can change items after the list is created.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']You can also change several items at once using slicing (explained next).
Slicing Lists
Slicing lets you get a part (sub-list) of a list.
General form:
$$
\text{list}[start:end]
$$
startindex is includedendindex is excluded
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30] (from start to index 2)
print(numbers[2:]) # [30, 40, 50] (from index 2 to end)You can also use slices to replace multiple items:
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] = [10, 11, 12]
print(numbers) # [0, 10, 11, 12, 4, 5]Adding Items to a List
`append()` – add to the end
append() adds a single item to the end of the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']`insert()` – add at a specific position
insert(index, item) inserts an item at a specific position, moving later items to the right.
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(fruits) # ['apple', 'banana', 'cherry']`extend()` – add multiple items
extend() adds all items from another list (or any iterable) to the end.
fruits = ["apple", "banana"]
more_fruits = ["cherry", "date"]
fruits.extend(more_fruits)
print(fruits) # ['apple', 'banana', 'cherry', 'date']Removing Items from a List
`remove()` – remove by value
Removes the first matching value.
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits) # ['apple', 'cherry', 'banana']
If the value is not in the list, remove() causes an error.
`pop()` – remove by index
Removes and returns the item at a given index. If no index is given, removes the last item.
fruits = ["apple", "banana", "cherry"]
last = fruits.pop()
print(last) # cherry
print(fruits) # ['apple', 'banana']
first = fruits.pop(0)
print(first) # apple
print(fruits) # ['banana']`del` – delete by index or slice
del is a Python keyword used to delete items.
numbers = [10, 20, 30, 40, 50]
del numbers[1] # delete item at index 1
print(numbers) # [10, 30, 40, 50]
del numbers[1:3] # delete a slice
print(numbers) # [10, 50]`clear()` – remove all items
Empties the list but keeps the list object.
numbers = [1, 2, 3]
numbers.clear()
print(numbers) # []Checking if an Item Is in a List
Use the in keyword to test if a value exists in the list.
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("orange" in fruits) # False
if "apple" in fruits:
print("We have apples!")Getting the Length of a List
Use len() to find out how many items are in a list.
fruits = ["apple", "banana", "cherry"]
count = len(fruits)
print(count) # 3Looping Over a List
You will learn loops in detail elsewhere, but here is how they commonly work with lists.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)This prints each item in the list, one per line.
Sorting and Reversing Lists
`sort()` – sort the list in place
sort() changes the existing list into a sorted version.
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers) # [1, 1, 3, 4, 5]
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits) # ['apple', 'banana', 'cherry']You can sort in reverse order:
numbers = [3, 1, 4, 1, 5]
numbers.sort(reverse=True)
print(numbers) # [5, 4, 3, 1, 1]`sorted()` – return a new sorted list
sorted() does not change the original list; it returns a new one.
numbers = [3, 1, 4, 1, 5]
sorted_numbers = sorted(numbers)
print(numbers) # [3, 1, 4, 1, 5]
print(sorted_numbers) # [1, 1, 3, 4, 5]`reverse()` – reverse the list order
Reverses the list in place, without sorting.
numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers) # [4, 3, 2, 1]Copying Lists
Assigning one list to another variable does not make a copy; it makes a second name for the same list.
a = [1, 2, 3]
b = a # NOT a copy!
b.append(4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3, 4]To make a real (shallow) copy, use one of these:
a = [1, 2, 3]
b = a.copy()
# or
b = list(a)
# or
b = a[:] # slice from start to end
b.append(4)
print(a) # [1, 2, 3]
print(b) # [1, 2, 3, 4]Joining and Repeating Lists
Joining lists with `+`
a = [1, 2]
b = [3, 4]
c = a + b
print(c) # [1, 2, 3, 4]Repeating lists with `*`
zeros = [0] * 5
print(zeros) # [0, 0, 0, 0, 0]Useful List Methods (Overview)
Some common list methods you have seen or will see:
append(x)– addxto the endinsert(i, x)– insertxat positioniextend(iterable)– add all items from another iterableremove(x)– remove the first occurrence ofxpop([i])– remove and return item at indexi(or last item)clear()– remove all itemsindex(x)– get the index of the first occurrence ofxcount(x)– count how many timesxappearssort()– sort the listreverse()– reverse the listcopy()– return a shallow copy
Example of index() and count():
numbers = [1, 2, 3, 2, 2, 4]
print(numbers.index(3)) # 2 (position of first 3)
print(numbers.count(2)) # 3 (three 2's)Simple Practice Ideas with Lists
Some small ideas to practice working with lists:
- Store a list of your favorite movies and:
- Add a new movie
- Remove one you no longer like
- Print how many movies are in the list
- Ask the user for 3 numbers, store them in a list, and:
- Print the list
- Print the smallest and largest number (using
min()andmax()) - Create a list of names and:
- Sort them
- Print them one per line using a
forloop
Lists are a core part of Python programming, and you will use them again in loops, functions, file handling, and many later topics.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!