
- 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
Sort Array By Parity in Python
Suppose, we have an array A with some numbers. We have to arrange the numbers as even then odd. So put the even numbers at first, then the odd numbers. So if the array is like A = [1, 5, 6, 8, 7, 2, 3], then the result will be like [6, 8, 2, 1, 5, 7, 3]
To solve this, we will follow these steps −
- set i := 0 and j := 0
- while j < size of arr
- if arr[j] is even, then seap arr[i] and arr[j], and increase i by 1
- increase j by 1
- return arr
Example
Let us see the following implementation to get better understanding −
class Solution(object): def sortArrayByParity(self, a): i = 0 j =0 while j < len(a): if a[j]%2==0: a[i],a[j] = a[j],a[i] i+=1 j+=1 return a ob1 = Solution() print(ob1.sortArrayByParity([1,5,6,8,7,2,3]))
Input
[1,5,6,8,7,2,3]
Output
[6,8,2,5,7,1,3]
- Related Articles
- Program to sort an array based on the parity values in Python
- Program to sort array by increasing frequency of elements in Python
- Relative Sort Array in Python
- Sort MongoDB Collection by Array value?
- Sort array by month-year JavaScript
- C program to sort an array by using merge sort
- Sort multidimensional array by multiple keys in PHP
- Sort by index of an array in JavaScript
- Python – Sort by range inclusion
- Python – Sort by Uppercase Frequency
- Python – Sort Dictionaries by Size
- Write a Python code to sort an array in NumPy by the nth column?
- Sort Tuples by Total digits in Python
- Python – Sort by Maximum digit in Element
- Sort array by year and month JavaScript

Advertisements