0

I have been studying different ways of manipulating lists for awhile now and I have encountered a problem that my inexperienced self cannot seem to solve.

Consider the list a = [1,0,1,0,1,1,0].

I want to push all occurrences of 1s to the left making the list a = [1,1,1,1,0,0,0].

Is there some function out there I could call that I am not aware of, or do I have to do this manually? I want to iterate through the list one by one but I feel like it wouldn't be efficient.

Parsher
  • 56
  • 4
  • 2
    Isn't this just sorting the list? In this case, sort in reverse order.`a.sort(reverse=True)` – Craig Jan 25 '20 at 15:26
  • Does this answer your question? [Sort a list in python](https://stackoverflow.com/questions/19199984/sort-a-list-in-python) – Tomerikoo Jan 25 '20 at 15:36

2 Answers2

0

How about this?

a.sort(key=lambda x:x!=1)

Change 1 to any other value you want to move.

korakot
  • 37,818
  • 16
  • 123
  • 144
  • Is there a way to move the 1's n amount of times starting from the right? E.g. a = [1,0,1,0,0,1,1,1] to a = [1,1,1,1,0,1,0,0] with n = 2? – Parsher Jan 25 '20 at 15:54
  • You can do some game with slicing like `a[-2:] + a[:-2]` in this case – mathfux Jan 25 '20 at 16:00
0

Since sorting is a good solution in this case, it's not working in general. If your list contains more elements than just 0 and 1, you would like to concatenate all 1s found with a new list that is formed after elimination of these 1s like so:

result = [1]*a.count(1)+list(filter(lambda x: x!=1, a))

Output for a = [1,2,3,5,2,1,1,4] is [1, 1, 1, 2, 3, 5, 2, 4] then.

mathfux
  • 5,759
  • 1
  • 14
  • 34