Python provides two methods to modify list elements. You can modify a single element at a time, or you can modify a group (multiple) elements at a time.
Modifying a single element is very simple, just assign a value to the element directly. Consider the following example:
name = ["Jason", "Alice", "Mark", "Iven", "Peggy"] name [2] = "Nicole" #Use positive index name [-3] = "Susan" #Use negative index print (name)
The output is:
['Jason', 'Alice', 'Susan', 'Iven', 'Peggy']
After using the index to get the list element, the value of the element is changed by = assignment.
Python supports assigning values to a set of elements using a slice syntax. When performing this operation, if you do not specify a step size (step parameter), Python does not require that the number of newly assigned elements is the same as the number of original elements; this means that this operation can add elements to the list or Remove elements from the list.
The following code shows how to modify the value of a group of elements:
name = ["Jason", "Alice", "Mark", "Iven", "Peggy"] #Modify the value of the 1st to 3rd elements (excluding the 3rd element) name [1: 3] = ["Nicole", "Kevin", "Peter"] print (name)
The output is:
['Jason', 'Nicole', 'Kevin', 'Peter', 'Iven', 'Peggy']
Assigning an empty slice is equivalent to inserting a new set of elements:
name = ["Jason", "Alice", "Mark", "Iven", "Peggy"] #Insert elements in 4 positions name [4: 4] = ["Nicole", "Kevin", "Peter"] print (name)
The output is:
['Jason', 'Alice', 'Mark', 'Iven', 'Nicole', 'Kevin', 'Peter', 'Peggy']
Python does not support single values when using slice syntax assignment. For example, the following is wrong:
name = ["Jason", "Alice", "Mark", "Iven", "Peggy"] #Insert elements in 4 positions name [4:4] = 33 print (name)
The output is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
[ipython-input-88-d4846c25935b] in [module]
1 name = ["Jason", "Alice", "Mark", "Iven", "Peggy"]
2 #Insert elements in 4 positions
----> 3 name [4:4] = 33
4 print (name)
TypeError: can only assign an iterable
But if you use string assignment, Python will automatically convert the string into a sequence, where each character is an element, please see the following code:
s = list("Python") s[2:4] = "abc" print(s)
The output is:
['P', 'y', 'a', 'b', 'c', 'o', 'n']
You can also specify the step size (step parameter) when using the slice syntax, but this time requires that the number of new elements assigned is the same as the number of original elements.
nums = [21, 35, 79, 8, 116, 90, 3] #Step length is 2, assign values to the 1, 3, and 5 elements nums [1: 6: 2] = [0.23, -19, 70.8] print (nums)
The output is:
[21, 0.23, 79, -19, 116, 70.8, 3]
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises