0
0
Pythonprogramming~5 mins

List mutability in Python

Choose your learning style9 modes available
Introduction

Lists can be changed after they are created. This helps us update, add, or remove items easily.

When you want to keep a collection of items that can change over time.
When you need to update a value in a list without making a new list.
When you want to add or remove items from a list during a program.
When you want to sort or reorder items in a list.
When you want to share a list between parts of a program and have changes seen everywhere.
Syntax
Python
my_list = [1, 2, 3]
my_list[0] = 10  # Change first item
my_list.append(4)  # Add new item
my_list.remove(2)  # Remove item with value 2

Lists use square brackets [] and can hold any type of items.

You can change items by their position (index) or use methods like append() and remove().

Examples
Start with an empty list and add one item.
Python
my_list = []
my_list.append(5)
print(my_list)
Change the only item in a list.
Python
my_list = [10]
my_list[0] = 20
print(my_list)
Change the last item in a list.
Python
my_list = [1, 2, 3]
my_list[2] = 30
print(my_list)
Remove an item by value.
Python
my_list = [1, 2, 3]
my_list.remove(2)
print(my_list)
Sample Program

This program shows how to change, add, and remove items in a list. It prints the list before and after each change.

Python
def print_list_state(description, some_list):
    print(f"{description}: {some_list}")

my_list = [5, 10, 15]
print_list_state("Original list", my_list)

# Change the first item
my_list[0] = 50
print_list_state("After changing first item", my_list)

# Add a new item
my_list.append(20)
print_list_state("After adding new item", my_list)

# Remove an item
my_list.remove(10)
print_list_state("After removing an item", my_list)
OutputSuccess
Important Notes

Changing an item by index is very fast (constant time).

Adding or removing items can take longer if the list is big.

Remember, if you assign a list to another variable, both variables point to the same list. Changing one changes the other.

Use list mutability when you want to update data without making a new list each time.

Summary

Lists can be changed after creation; this is called mutability.

You can update items by position, add new items, or remove items.

Mutability helps keep your program flexible and efficient.