What is the method for indexing lists in Python?
In Python, you access elements in a list by using square brackets ([]). Indexing starts at 0, so the first element has an index of 0, the second element has an index of 1, and so on. You can use both positive and negative indexing to access elements in a list.
Use positive index:
- Using the list name and index value, for example: my_list[0] accesses the first element, my_list[1] accesses the second element.
Using negative indices:
- Use negative indices to access elements from the end of a list, for example: my_list[-1] accesses the last element, my_list[-2] accesses the second-to-last element.
One way to access a subset of a list is by using slicing. Slicing uses a colon (:) to specify a starting index and ending index, where the starting index indicates the first element to include in the slice and the ending index indicates the element to exclude from the slice. For example, my_list[2:5] returns the elements from index 2 to index 4 (excluding index 5).