Search code examples
pythonpython-3.xfunctionreturn

Why the function is not returning the desired list?


My code:

directions = ["north", "south", "east", "west"]
def scan(sentence):
    global sentence_list
    sentence_list = []
    sentence.split()
    for i in sentence:
        if i in directions:
            a = ('direction', i)
            sentence_list.append(a)
            del a
    return sentence_list

I am trying to split a string and return the words in a tuple within a list, but whenever i test it using returns empty list.

Here's my output:

PS C:\Users\dell 3521\lpythw\ex48> nosetests
F
======================================================================
FAIL: tests.lexicon_tests.test_directions
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\dell 3521\AppData\Local\Programs\Python\Python36- 
 32\lib\site-packages\nose-1.3.7-py3.6.egg\nose\case.py
    ", line 198, in runTest
    self.test(*self.arg)
  File "C:\Users\dell 3521\lpythw\ex48\tests\lexicon_tests.py", line 5, in 
test_directions
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
AssertionError: Lists differ: [] != [('direction', 'north')]

Second list contains 1 additional elements.
First extra element 0:
('direction', 'north')

- []
+ [('direction', 'north')]

----------------------------------------------------------------------
Ran 1 test in 0.021s

FAILED (failures=1)

Thanks in advance.


Solution

  • You have to reassign sentence to the return value of sentence.split() or iterate directly over sentence.split(), because the str.split() method does not modify sentence in place, but returns a list instead.

    Also you do not need the del a statement.

    Change your code to

    directions = ["north", "south", "east", "west"]
    
    def scan(sentence):
        global sentence_list
        sentence_list = []
        for i in sentence.split():
            if i in directions:
                a = ('direction', i)
                sentence_list.append(a)
    
        return sentence_list 
    

    Or a even shorter way is using list comprehension

    directions = ["north", "south", "east", "west"]
    
    def scan(sentence):
        global sentence_list
        sentence_list = [('direction', i) for i in sentence.split() if i in directions]
    
        return sentence_list
    

    The output is

    >>> scan("north")
    [('direction', 'north')]
    

    And you may want the over think the use of the global statement in your code. As explained in various resources, you want to avoid using global variables for the readability and maintainability of your code.