A list in Python is an ordered collection of elements where each element is stored as a scalar value and assigned an index. The indexing starts at 0, meaning the first element is at index 0, the second at index 1, and so on. You can easily access and modify list elements by specifying their index within square brackets.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
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.