Accessing elements in a list is straightforward in Python.
- Accessing by Index
- You can access elements using their index. Indexing starts at 0.
my_list = [10, 20, 30, 40, 50] print(my_list[0]) # Output: 10 print(my_list[3]) # Output: 40
- Negative Indexing
- Negative indices can be used to access elements from the end of the list.
my_list = [10, 20, 30, 40, 50] print(my_list[-1]) # Output: 50 print(my_list[-2]) # Output: 40
- Slicing
- You can access a range of elements using slicing. The syntax is
list[start:stop:step]
. my_list = [10, 20, 30, 40, 50] print(my_list[1:4]) # Output: [20, 30, 40] print(my_list[:3]) # Output: [10, 20, 30] print(my_list[::2]) # Output: [10, 30, 50]
- You can access a range of elements using slicing. The syntax is