Reverse Words in a String: Why my Python Code has an UnboundLocalError

  • 0

    The following code runs successfully in my local Python 2.7 IDLE, but it has an UnboundLocalError ( local variable 'new_string' referenced before assignment) in this interpreter. What happened? What should I do?

    class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        word_list = s.split()
        wordnum = len(word_list)
        for i in range(wordnum):
            if i == 0:
                new_string = word_list[wordnum - i - 1]
                new_string = new_string + ' ' + word_list[wordnum - i - 1]
        self.answer = new_string
        return self.answer

  • 0

    This has to do with the variable scoping in Python 3. Since the "new_string" variable is only ever defined in your "for" loop, it is only available in the for loop.

    You could simply add "new_string = None" right before your for loop, which would make the variable accessible from within the for loop and also outside of it.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.