Some of the elements that work with python, called slices.
Create slices
Specifies the index of the first element and the last element to use, like the range () function, where Python stops after reaching the element that precedes the second index you specify.
Define a list first vegetables
vegetables = ['tomato','bean','potato ','onion','radish']
Take the 1th to 3rd element out of the
Print (Vegetables[0:3])
Take the 2nd to 4th element out of the
Print (Vegetables[1:4])
Remove the first 4 elements
Print (Vegetables[:4])
Remove all elements after the 2nd element (including 2nd)
Print (vegetables[2:])
Remove the last three elements
Print (vegetables[-3:])
Copy List
To copy a slice, create a slice that contains the entire list by omitting both the start index and the Terminate index [:], which allows Python to create a slice that starts with the first element and terminates at the last element, that is, copying the entire list.
Fruits = ['aplle','pear','lemon' ,'peach'= fruits[:]print(fruitsfoot_ Copy
Perhaps from the above case we have no way to see that there are 2 lists, the following example can better explain
Fruits = ['Aplle','Pear','Lemon','Peach']fruits_copy=Fruits[:]fruits.append ('Grape') Fruits_copy.append ('Banana')Print(fruits)Print(fruits_copy)
Printing results:
[' Aplle ', ' pear ', ' lemon ', ' peach ', ' grape ']
[' Aplle ', ' pear ', ' lemon ', ' peach ', ' banana ']
This means that the list is indeed copied.
The following is a wrong case
fruits = [ " aplle " , " pear " , " lemon ", " peach Span style= "COLOR: #800000" > " ]fruits_copy = fruits
fruits.append ('grape') fruits_copy.append ('Banana ')print(fruits)print(fruits_copy)
Printing results:
[' Aplle ', ' pear ', ' lemon ', ' peach ', ' grape ', ' banana ']
[' Aplle ', ' pear ', ' lemon ', ' peach ', ' grape ', ' banana ']
This assigns the fruits to fruits_copy instead of storing the fruits copy to the fruits_copy.
"Python" slice