web123456

List list modification element in python

Python provides two ways to modify list elements. You can modify a single element or multiple elements at a time.

Modify a single element

Modify a single element and directly assign values ​​to the element

Example:

list = ["python",1,2,"java",78,9,80,90,2,34,2]
print(list)
list[0] = 1
print(list)

Running results:

['python', 1, 2, 'java', 78, 9, 80, 90, 2, 34, 2]
[1, 1, 2, 'java', 78, 9, 80, 90, 2, 34, 2]

After using the index to obtain the list element, the value of the element is changed by assigning the = value

Modify multiple elements

Python supports assigning values ​​to a group of elements through edge cleavage syntax. When performing this operation, if the step size is not specified, python does not require the number of newly assigned elements to be the same as the original number of elements; this means that this operation can either add elements to the list or delete elements for the list.

Example:

list = ["python",1,2,"java",78,9,80,90,2,34,2]
 print(list)
 #Modify the first element to the fifth element (not including the fifth element)
 list[0:4] = [1,2,3,4]
 print(list)

Running results:

['python', 1, 2, 'java', 78, 9, 80, 90, 2, 34, 2]
[1, 2, 3, 4, 78, 9, 80, 90, 2, 34, 2]

If you assign a value to an empty slice, it is equivalent to inserting a new set of elements.

Example:

list = ["python",1,2,"java",78,9,80,90,2,34,2]
 print(list)
 # Assigning a value to an empty slice is equivalent to inserting a new set of elements
 list[4:4] = [1,2,3,4]
 print(list)

Running results:

['python', 1, 2, 'java', 78, 9, 80, 90, 2, 34, 2]
['python', 1, 2, 'java', 1, 2, 3, 4, 78, 9, 80, 90, 2, 34, 2]

When using slice syntax assignment, python does not support a single value, for example: list[4:4] = 33 is wrong.

But if you use string assignment, python will automatically convert the string into a sequence, where each character is an element

Example

list = ["python",1,2,"java",78,9,80,90,2,34,2]
print(list)
list[2:4] = "xyz"
print(list)

Running results:

['python', 1, 2, 'java', 78, 9, 80, 90, 2, 34, 2]
['python', 1, 'x', 'y', 'z', 78, 9, 80, 90, 2, 34, 2]

When using slice syntax, you can also specify the step size (step parameter), but this must require that the number of new elements assigned is the same as the number of original elements.

Example:

list = ["python",1,2,"java",78,9,80,90,2,34,2]
print(list)
list[1:6:2] = [3,4,5]
print(list)

Running results:

['python', 1, 2, 'java', 78, 9, 80, 90, 2, 34, 2]
['python', 3, 2, 4, 78, 5, 80, 90, 2, 34, 2]