List type, tuple type 2
Unpack assignment Unpacked assignment is a function similar to assignment using slices. It is a function to enter multiple elements on the left and right of the equal and assign to multiple elements at once. Note that in unpacked assignment, an error will occur if the number of elements is not the same on the left and right of the equal. With unpacked assignment, you can perform variable swap (Swap) in one shot as follows. There is no need to save the element using variables etc. [Use unpacked substitution] a = 1 b = 2 b, a = a, b print(a, b) ↓ 2 1
Number of slice steps In fact, you can give three parameters separated by a colon (:) to give to a slice. The third number is treated as a step. You can specify "take out elements while skipping n" in the slice. [Extract elements from the list by slicing] a = [1, 2,3 ,4, 5] a ↓ [1, 2, 3, 4, 5]
a[1:4] ↓ [2, 3, 4]
a[2:100] ↓ [3, 4, 5]
a[::2] ↓ [1, 3, 5]
Assigning and deleting elements using slices You can combine slices and assignments to replace multiple elements of a list at once. Specify the element you want to replace in a slice and place it to the left of the equal. Place the element you want to replace to the right of the equal. The element on the right should be a sequence such as a list or tuple. [Adding elements] a = [1, 2, 3, 4, 5] a[2:4] = [’Three’, ‘Four’, ‘Five’] a ↓ [1, 2, ’Three’, ‘Four’, ‘Five’, 5]
On the left side of the equal, the second and third elements (counting from 0) are specified in slices. The element on the right specifies a list with three strings. Even if the number of elements on the left and right is different, it will automatically process to maintain consistency. You can remove multiple elements at once by combining a del statement with a slice. [Delete element] a = [1, 2, 3, 4, 5] del a[2:] a ↓ [1, 2]
Recommended Posts