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
EasyCreate a function named change_element that modifies a list by replacing one element with a new value.
Function Parameters:
lst- the list to modifyindex- the position of the element to replacenew_element- the new value to put in that position
What the function should do:
- Take the element at the specified index in the list
- Replace it with the new element
- 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 hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input11Lists Basics
Declaring a ListAccessing List ElementsModifying ListsList MethodsRecap - Product ListRecap - Reversed ListTuple3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2