- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

[8,5,3,4,8,9,3,6,4,7]

[3, 4, 8, 5, 3, 6, 8, 9, 4, 7]

- Related Questions & Answers
- Swapping even and odd index pairs internally in JavaScript
- Python program to count pairs for consecutive elements
- Program to maximize the number of equivalent pairs after swapping in Python
- Program to find array of doubled pairs using Python
- Program to count index pairs for which array elements are same in Python
- Program to equal two strings of same length by swapping characters in Python
- Max Number By Swapping
- Program to Find K-Largest Sum Pairs in Python
- Program to find number of good pairs in Python
- Program to check if array pairs are divisible by k or not using Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find smallest index for which array element is also same as index in Python
- Index Pairs of a String in Python
- Program to count nice pairs in an array in Python
- Program to find length of longest consecutive sequence in Python

Advertisements