Python Change Elements in List


Changing elements in a list is straightforward in Python.

  1. Modifying by Index
    1. You can change an element by accessing it via its index.
    2. my_list = [10, 20, 30, 40, 50]
      my_list[1] = 25
      print(my_list)  # Output: [10, 25, 30, 40, 50]
      
  2. Changing a Range of Elements
    1. You can change multiple elements using slicing.
    2. my_list = [10, 20, 30, 40, 50]
      my_list[1:3] = [25, 35]
      print(my_list)  # Output: [10, 25, 35, 40, 50]
      


Using List Methods

You can also change elements using various list methods.

  1. append()
    1. Adds an element to the end of the list.
    2. my_list = [10, 20, 30]
      my_list.append(40)
      print(my_list)  # Output: [10, 20, 30, 40]
      
  2. extend()
    1. Extends the list by appending elements from another iterable.
    2. my_list = [10, 20, 30]
      my_list.extend([40, 50])
      print(my_list)  # Output: [10, 20, 30, 40, 50]
      
  3. insert()
    1. Inserts an element at a specified position.
    2. my_list = [10, 20, 30]
      my_list.insert(1, 15)
      print(my_list)  # Output: [10, 15, 20, 30]
      
  4. remove()
    1. Removes the first occurrence of a value.
    2. my_list = [10, 20, 30, 20]
      my_list.remove(20)
      print(my_list)  # Output: [10, 30, 20]
      
  5. pop()
    1. Removes and returns an element at a specified position (default is the last element).

    2. my_list = [10, 20, 30]
      popped_element = my_list.pop(1)
      print(popped_element)  # Output: 20
      print(my_list)         # Output: [10, 30]
      

These methods allow you to efficiently modify elements within a list in Python.