Creating a List
Consider the following example of a list containing country names:Modifying List Elements
To modify an element in a list, assign a new value to the desired index. For example, to change “USA” (at index 0) to “UK”, use the following code:Determining List Length
The built-inlen function is used to obtain the number of elements in a list. For instance, to get the length of the countries list:
3.
Removing Elements from a List
You can delete an element using thedel keyword. For example, to remove the second item (index 1) from the list:
Using Negative Indices
Python lists support negative indexing, which allows you to access elements from the end of the list. For example, to retrieve the last element:Handling Index Errors
Accessing an index that does not exist, such as trying to retrieve a fourth element from a three-element list, will result in an error. For example:Attempting to access an out-of-range index will raise an
IndexError: list index out of range. Always validate the existence of an element before accessing its index.