Python sequence slicing [ref]
Problem¶
- Return the first three values, the values from index
2onward, and the interior values of[0, 1, 2, 3, 4, 5]. - Reverse
[0, 1, 2, 3, 4, 5]with a slice. - Select the even-indexed values of
[0, 1, 2, 3, 4, 5]. - Return indices
1through3of"abcde". - Replace indices
1through3of[0, 1, 2, 3, 4, 5]with[10, 20]. - Assign
[1, 2, 3]to the even-indexed slots of[0, 0, 0, 0, 0].
Python solution¶
nums = [0, 1, 2, 3, 4, 5]
nums[:3] # [0, 1, 2]
nums[2:] # [2, 3, 4, 5]
nums[1:-1] # [1, 2, 3, 4]
nums[::-1] # [5, 4, 3, 2, 1, 0]
nums[::2] # [0, 2, 4]
"abcde"[1:4] # 'bcd'; stop index is excluded
nums = [0, 1, 2, 3, 4, 5]
nums[1:4] = [10, 20]
nums # [0, 10, 20, 4, 5]
nums = [0, 0, 0, 0, 0]
nums[::2] = [1, 2, 3] # Extended slice requires exactly three replacements.
nums # [1, 0, 2, 0, 3]
Links¶
- 189. Rotate Array (Top Easy)
- 28. Find the Index of the First Occurrence in a String (Top Easy)
- 324. Wiggle Sort II (Top Hard)
- Top-down merge sort (DSA)