Menu
Coddy logo textTech

Modifying Lists

Part of the Fundamentals section of Coddy's Python journey — lesson 55 of 77.

In addition to accessing the elements of a list, you can also modify them. To modify a specific element in a list, you can assign a new value to it using its index.

Here's an example:

my_list = ["apple", "banana", "cherry"]
my_list[1] = "orange"
print(my_list)

Output:

["apple", "orange", "cherry"]

banana was changed to an orange

challenge icon

Challenge

Easy

Create a function named change_element that modifies a list by replacing one element with a new value.

Function Parameters:

  • lst - the list to modify
  • index - the position of the element to replace
  • new_element - the new value to put in that position

What the function should do:

  1. Take the element at the specified index in the list
  2. Replace it with the new element
  3. Return the modified list

Example: change_element([1, 2, 3], 0, 9) should return [9, 2, 3] because it replaces the element at index 0 (which was 1) with 9.

Cheat sheet

To modify a specific element in a list, use its index:

my_list = ["apple", "banana", "cherry"]
my_list[1] = "orange"
print(my_list)  # Output: ["apple", "orange", "cherry"]

This changes the element at index 1 from "banana" to "orange".

Try it yourself

def change_element(lst, index, new_element):
    # Write code here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals