Python From Beginner to Advanced

0% completed

Previous
Next
Python - Updating a List

Lists in Python are mutable, which means their elements can be modified after creation. Updating a list allows changing specific elements without altering the overall structure. This can be done by assigning new values to existing indexes or modifying multiple elements at once using slicing.

1. Updating a List Using Positive Indexing

Positive indexing is the standard method of accessing elements in a list, starting from 0 for the first element, 1 for the second, and so on. When updating a list using positive indexing, you directly assign a new value to a specific position in the list. This method is useful when you know the exact index of the element that needs to be changed.

Example 1: Updating a Single Element Using Positive Indexing

Python3
Python3

. . . .

Explanation

  • The original list contains ["Apple", "Banana", "Cherry"].
  • my_list[1] = "Mango" replaces "Banana" (at index 1) with "Mango".
  • The updated list becomes ['Apple', 'Mango', 'Cherry'].

2. Updating a List Using Negative Indexing

Negative indexing provides a way to access and modify elements from the end of the list, where -1 refers to the last element, -2 to the second-last, and so on. This approach is especially useful when working with lists of unknown or dynamic lengths, as it allows modifying elements without counting from the beginning.

Example 2: Updating a Single Element Using Negative Indexing

Python3
Python3

. . . .

Explanation

  • The original list is ["Apple", "Banana", "Cherry"].
  • my_list[-1] = "Grapes" updates the last element (Cherry) to "Grapes".
  • The updated list becomes ['Apple', 'Banana', 'Grapes'].

3. Updating Multiple Elements Using Slicing

Slicing allows modifying multiple elements at once by selecting a portion of the list and assigning new values. Unlike single-element updates, slicing replaces a group of elements in a single step. This method is useful when updating a specific range of values in a list.

Example 3: Updating Multiple Elements Using Slicing

Python3
Python3

. . . .

Explanation

  • The original list is [10, 20, 30, 40, 50].
  • numbers[1:4] = [25, 35, 45] replaces the elements at indices 1 to 3 (20, 30, 40) with [25, 35, 45].
  • The updated list becomes [10, 25, 35, 45, 50].

4. Replacing All Elements in a List

Instead of modifying individual elements, Python allows replacing all elements in a list at once. This is done by assigning a new list to the entire slice ([:]), effectively keeping the same list reference while changing its content.

Example 4: Replacing All Elements

Python3
Python3

. . . .

Explanation:

  • The original list is ["Red", "Green", "Blue"].
  • colors[:] = ["Yellow", "Purple", "Cyan"] replaces all elements in the list.
  • The updated list becomes ['Yellow', 'Purple', 'Cyan'].

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next