- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap Even Index Elements And Odd Index Elements in Python
Suppose we have a list of numbers called nums, we will exchange each consecutive even indexes with each other, and also exchange each consecutive odd index with each other.
So, if the input is like [1,2,3,4,5,6,7,8,9], then the output will be [3, 4, 1, 2, 7, 8, 5, 6, 9]
To solve this, we will follow these steps −
- length := size of nums
- for i in range 0 to length, increase by 4, do
- if i+2<length, then
- exchange nums[i] and nums[i+2]
- if i+3<length, then
- exchange nums[i+1] and nums[i+3]
- if i+2<length, then
- return nums
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): length = len(nums) for i in range(0,length,4): if(i+2<length): nums[i], nums[i+2] = nums[i+2], nums[i] if(i+3<length): nums[i+1], nums[i+3] = nums[i+3], nums[i+1] return nums ob = Solution() nums = [1,2,3,4,5,6,7,8,9] print(ob.solve(nums))
Input
[1,2,3,4,5,6,7,8,9]
Output
[3, 4, 1, 2, 7, 8, 5, 6, 9]
- Related Articles
- Rearrange array such that even index elements are smaller and odd index elements are greater in C++
- Even numbers at even index and odd numbers at odd index in C++
- Swap Consecutive Even Elements in Python
- Odd even index difference - JavaScript
- Python – Elements with same index
- Python - Index Directory of Elements
- Python - Index Ranks of Elements
- Swapping even and odd index pairs internally in JavaScript
- Find even odd index digit difference - JavaScript
- Python - Make new Pandas Index with deleting multiple index elements
- Equate two list index elements in Python
- Sorting odd and even elements separately JavaScript
- Python – Check if elements index are equal for list elements
- Python Pandas - Repeat elements of an Index
- Python – Check if elements in a specific index are equal for list elements

Advertisements