Python Lists: Modifying, Adding, Removing Objects & Quick Practice Programs
Lists Can Be Modified
Python lists are mutable.
Mutable means that we can change the objects stored in a list after the list has been created.
For example:
Output:
Originally:
After changing the object at index 2:
The third object has been changed from 30 to 100.
Adding an Object to a List
We can add a new object to the end of a list using append().
Example:
Output:
Before append():
After:
The object 40 has been added to the end.
Removing an Object from a List
We can remove an object using remove().
Output:
The object 30 has been removed.
Changing Multiple Objects
Because lists are mutable, we can change their objects.
Output:
An Empty List
A list does not have to contain objects when it is created.
Output:
We can later add objects:
Output:
Important Properties of Python Lists
We can summarize the basic properties of lists as follows:
1. Lists store multiple objects
A list can store multiple objects in a single variable.
2. Lists are ordered
The objects have a specific order.
The order of objects is maintained in the list.
3. Lists use square brackets
A list is created using square brackets [ ].
The opening and closing [ ] identify a list.
4. Lists allow duplicate objects
A list can contain the same object multiple times.
For example:
Output:
The value 10 can appear multiple times.
5. Lists can contain different types of objects
A list can contain objects of different data types.
Here, the list contains an integer, float, string, and Boolean value.
6. Lists are mutable
Objects in a list can be changed, added, or removed after the list is created.
The value at index 1 can be changed from 20 to 50.
7. Lists use zero-based indexing
The first object in a list has index 0.
Therefore, the first object has index 0, the second has index 1, and so on.
A Simple Real-World Example
Suppose we want to store the marks of five students:
Output:
Quick Practice Programs
Try running these programs yourself: