Python Access Elements in List


Accessing elements in a list is straightforward in Python. 

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