Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append zero but not False in a list python

Tags:

python

list

I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?

def move_zeros(array):
    #your code here
    for i in array:
        if i == 0:
            array.remove(i)
            array.append(i)
    answer = array
    print answer

move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])

This is what it returns when you run it.

['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0]
like image 839
Dane Barnett Avatar asked Sep 05 '16 13:09

Dane Barnett


People also ask

What happens if you append none to a list Python?

The Python append() method returns a None value. This is because appending an item to a list updates an existing list. It does not create a new one. If you try to assign the result of the append() method to a variable, you encounter a “TypeError: 'NoneType' object has no attribute 'append'” error.

Is 0 A valid list in Python?

The sum of an empty list, or a list filled with zeroes, is 0 which is Falsey. Alternatively if you're just scared about the zero division, you can skip all the conditionals and simply try it, excepting out the case where you might divide by zero. This is a common idiom in Python.

What does append () do in Python?

Append in Python is a pre-defined method used to add a single item to certain collection types. Without the append method, developers would have to alter the entire collection's code for adding a single value or item.

What is the opposite of append in Python?

pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).


1 Answers

What you're doing is basically a custom sort. So just implement it this way:

array.sort(key=lambda item: item == 0 and not isinstance(item, bool))

What this means is "Transform the array into a boolean one where items which are 0 are True and everything else is False." Then, sorting those booleans puts all the False values at the left (because they are like 0), and the True values at the right (like 1).


Originally I had written a solution which is not supported in Python 3:

array.sort(lambda L,R: -1 if R is 0 else 0)

What this means is "L is less than R if R is 0". Then we sort according to that. So we end up with any zeros on the right, because anything is less than them. The above only works in Python 2, however.

like image 72
John Zwinck Avatar answered Oct 20 '22 15:10

John Zwinck