
- 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
Swap Consecutive Even Elements in Python
Suppose we have a list of numbers called nums, we have to exchange every consecutive even integer with each other.
So, if the input is like nums = [4, 5, 6, 8, 10], then the output will be [6, 5, 4, 10, 8]
To solve this, we will follow these steps −
- temp := null
- for i in range 0 to size of nums, do
- if nums[i] mod 2 is same as 0, then
- if temp is not null, then
- exchange nums[i], nums[temp]
- temp := null
- otherwise,
- temp := i
- if temp is not null, then
- if nums[i] mod 2 is same as 0, then
- return nums
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): temp = None for i in range(len(nums)): if nums[i] % 2 == 0: if temp is not None: nums[i], nums[temp] = nums[temp], nums[i] temp = None else: temp = i return nums ob = Solution() print(ob.solve([4, 5, 6, 8, 10]))
Input
[4, 5, 6, 8, 10]
Output
[6, 5, 4, 10, 8]
- Related Articles
- Swap Even Index Elements And Odd Index Elements in Python
- Consecutive elements pairing in list in Python
- Python – Filter consecutive elements Tuples
- Python – Reorder for consecutive elements
- Python – Consecutive identical elements count
- Python – Group Consecutive elements by Sign
- Python – Summation of consecutive elements power
- Check if array elements are consecutive in Python
- Python – Grouped Consecutive Range Indices of Elements
- Check if Queue Elements are pairwise consecutive in Python
- Python program to count pairs for consecutive elements
- Program to pack same consecutive elements into sublist in Python
- Maximum Swap in Python
- Program to find only even indexed elements from list in Python
- Consecutive elements sum array in JavaScript

Advertisements