Open In App

Segregate 0's and 1's in an array list - Python

Last Updated : 14 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Segregating 0s and 1s in an array involves rearranging the elements so that all 0s appear before 1s. This can be done using different methods, such as list comprehension, sort() method or a two-pointer approach, each offering varying levels of efficiency and simplicity

Using List Comprehension

To segregate 0s and 1s in an array using list comprehension, we can create two separate lists—one for 0s and one for 1s

Python
a = [0, 1, 1, 0, 1, 0, 1, 0]

# Separate 0's and 1's
result = [x for x in a if x == 0] + [x for x in a if x == 1]

print(result)  

Output
[0, 0, 0, 0, 1, 1, 1, 1]

Explanation:

  • List comprehension [x for x in a if x == 0] extracts all 0s from the list a, and [x for x in a if x == 1] extracts all 1s. These two separate lists ensure that 0s and 1s are grouped together.
  • + operator concatenates the two lists, resulting in a new list result where all 0s appear first, followed by all 1s. For the given a, the output will be [0, 0, 0, 0, 1, 1, 1, 1]

Using the sort() Method

Since 0's are less than 1's, sorting naturally groups them.

Python
a = [0, 1, 1, 0, 1, 0, 1, 0]

# Sort the array
a.sort()

print(a)  

Output
[0, 0, 0, 0, 1, 1, 1, 1]

Explanation:

  • sort() method rearranges the elements of the list a in ascending order, placing all 0s before 1s because 0 is less than 1.
  • The operation is performed in-place, meaning the original list a is modified directly. After sorting, the list becomes [0, 0, 0, 0, 1, 1, 1, 1]

Using Two Pointers

Efficient for large lists as it avoids additional memory allocation.

Python
a = [0, 1, 1, 0, 1, 0, 1, 0]

# Two-pointer approach
left, right = 0, len(a) - 1
while left < right:
    if a[left] == 1 and a[right] == 0:
        a[left], a[right] = a[right], a[left]
    if a[left] == 0:
        left += 1
    if a[right] == 1:
        right -= 1

print(a) 

Output
[0, 0, 0, 0, 1, 1, 1, 1]

Explanation

  • The two-pointer approach uses two pointers: left starts from the beginning and right starts from the end of the list. The loop continues until the left pointer is less than the right pointer.
  • Inside the loop, if a[left] is 1 and a[right] is 0, they are swapped. Then, the pointers are adjusted: left moves right when a[left] is 0, and right moves left when a[right] is 1. The result is a list where all 0s appear before 1s.

Article Tags :
Practice Tags :

Similar Reads