list.reverse does not return list?

56,412

Solution 1

You can use reversed(formation) to return a reverse iterator of formation. When you call formation.reverse() it does an in place reversal of the list and returns None.

EDIT:

I see what you are trying to do now, in my opinion it's easier to just do this with a list comprehension:

def solution(formation):
    return len([k for k in formation[formation.index(bCamel)+1:] if k == fCamel]) == 0

This basically looks at all the elements after the first bCamel and collects all the elements that have the value fCamel. If that list has a length == 0 you have a solution.

Here's a few examples:

>>> k = ['F','F','B','B','F']
>>> solution(k)
False
>>> k = ['F','F','B','B','B']
>>> solution(k)
True
>>> k = ['F','F','B','F','F','B','B']
>>> solution(k)
False
>>> 

Solution 2

You can use slicing to return the reversed list:

l[::-1]

Solution 3

To build on GWW's answer, if you want this code to work as is you would just do list(reversed(formation)). If you really want to be able to use formation.reverse() instead, you would have to subclass list:

>>> class ReversableList(list):
...     def reverse(self):
...         return list(reversed(self))
... 
>>> x = ReversableList([1,2,3])
>>> x.reverse()
[3, 2, 1]

Whether or not this is advisable is another question of course.

Solution 4

list.reverse reverses inplace. That is:

>>> l = [1, 2, 3]
>>> l.reverse()
>>> l
[3, 2, 1]

Please consult the Python documentation, things like these are laid out there. You can also try the 'help' built-in:

help(l.reverse) Help on built-in function reverse:

reverse(...) L.reverse() -- reverse IN PLACE

Solution 5

I just came across this problem and wanted to clarify some things for users new to python coming from a javascript background.

In javascript, a.reverse() reverses in place and also returns the array when called.

Javascript:

var a = [2, 3 ,4]
console.log(a.reverse())
// outputs [4, 3, 2]
console.log(a)
// outputs [4, 3, 2]

In python, a.reverse() reverses in place, but does not return the array. This is what caused confusion for me.

In python:

a = [2, 3, 4]
a.reverse()
print(a)
# outputs [4, 3, 2]
# can't do print(a.reverse())
Share:
56,412
nakiya
Author by

nakiya

Feeling lost in the land of gods

Updated on January 08, 2020

Comments

  • nakiya
    nakiya over 4 years

    The return object is named None for list.reverse(). So this code fails when I call solution(k). Is there any way I can get around making a temporary? Or how should I do it?

    fCamel = 'F'
    bCamel = 'B'
    gap = ' '
    
    k = ['F', ' ', 'B', 'F']
    
    def solution(formation):
        return ((formation.index(bCamel) > (len(formation) - 1 - (formation.reverse()).index(fCamel))))
    

    p.s. This is my first code in python. I thought it was functional.