About Lesson
๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Create and work with Python lists
-
Access and update list elements using indexes
-
Use common list methods like
append()
,remove()
,insert()
, andsort()
-
Iterate over lists and use slicing
๐ Lesson Content
๐น What is a List in Python?
A list is an ordered collection of items (data) that is mutable, meaning it can be changed after itโs created.
List Syntax:
โ Lists can contain different data types:
๐ธ Accessing Items in a List
Use indexing to access individual items. Indexing starts from 0.
๐ธ Modifying List Elements
โ Lists are mutable โ you can change elements.
๐ธ Common List Methods
Method | Description | Example |
---|---|---|
append(x) |
Adds item to the end | fruits.append("orange") |
insert(i, x) |
Inserts item at index i |
fruits.insert(1, "kiwi") |
remove(x) |
Removes first matching value x |
fruits.remove("banana") |
pop() |
Removes and returns the last item | fruits.pop() |
sort() |
Sorts list in ascending order | numbers.sort() |
reverse() |
Reverses the order | fruits.reverse() |
ย
๐ธ List Slicing
Slicing returns a portion of the list.
Slice | Meaning |
---|---|
list[start:end] |
from index start to end-1 |
list[:n] |
from beginning to index n-1 |
list[-1] |
last item in the list |
ย
๐ Looping Through a List
๐ง Mini Practice
๐ Assignment
Create a list of your 5 favorite books. Then:
-
Add a new book to the end
-
Change the third book title
-
Remove the second book
-
Print the list using a loop