
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find array by swapping consecutive index pairs in Python
Suppose we have a list of numbers called nums, we have to return the list by swapping each consecutive even indexes with each other, and swapping each consecutive odd indexes with each other.
So, if the input is like nums = [8,5,3,4,8,9,3,6,4,7], then the output will be [3, 4, 8, 5, 3, 6, 8, 9, 4, 7]
To solve this, we will follow these steps −
- for i in range 0 to size of nums - 2, increase by 4, do
- if i + 2 < size of nums, then
- swap nums[i] and nums[i + 2]
- if i + 3 < size of nums, then
- swap nums[i + 1] and nums[i + 3]
- if i + 2 < size of nums, then
- return nums
Example
Let us see the following implementation to get better understanding −
def solve(nums): for i in range(0, len(nums) - 2, 4): if i + 2 < len(nums): nums[i], nums[i + 2] = nums[i + 2], nums[i] if i + 3 < len(nums): nums[i + 1], nums[i + 3] = nums[i + 3], nums[i + 1] return nums nums = [8,5,3,4,8,9,3,6,4,7] print(solve(nums))
Input
[8,5,3,4,8,9,3,6,4,7]
Output
[3, 4, 8, 5, 3, 6, 8, 9, 4, 7]
- Related Articles
- Swapping even and odd index pairs internally in JavaScript
- Program to maximize the number of equivalent pairs after swapping in Python
- Python program to count pairs for consecutive elements
- Program to count index pairs for which array elements are same in Python
- Program to find array of doubled pairs using Python
- Program to find smallest index for which array element is also same as index in Python
- Program to count nice pairs in an array in Python
- Program to equal two strings of same length by swapping characters in Python
- Program to restore the array from adjacent pairs in Python
- Program to check if array pairs are divisible by k or not using Python
- Program to Find K-Largest Sum Pairs in Python
- Program to find number of good pairs in Python
- Index Pairs of a String in Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find maximum value at a given index in a bounded array in Python

Advertisements