Given a list nums, return a new list in which the elements at positions 0 and 1 are swapped, the elements at positions 2 and 3 are swapped, and so on. If the length is odd, the final element has no partner and stays in place.
Examples
Input: nums = [6, 1, 9, 4, 7]
Output: [1, 6, 4, 9, 7]
Input: nums = [5, 8, 2, 3]
Output: [8, 5, 3, 2]
Constraints
0 <= len(nums) <= 10**5- Return a new list; do not modify
nums. One test callsnums_after(nums), which runs yourswap_pairs, appends an item to the list you returned and then returnsnumsitself, so it must come back unchanged. - Target: O(n) time.
Goals
- Step through a list two elements at a time
- Swap values with tuple assignment
- Leave an unpaired last element alone