Blue Week Special Offer | Brighten your week!
days
hours
minutes
seconds

General Question: Assigning variables back to itself

So I am working on a guided project for statistical significance, but this is a more general question and not sure if it belongs here. Here is the link to it if helpful:

Anyways, I realized while working on this that almost always when applying a method to a variable, I assign the variable back to itself. This seems to be the right case most of the time, at least while working with pandas. However, while working on this project, I ran into an error an the solution was to not reassign the value.

Here is my code:

def answer_from_question(row):
    split_answer = row['clean_answer'].split()
    split_question = row['clean_question'].split()
    match_count = 0
    if 'the' in split_answer:
        split_answer.remove('the')
    if len(split_answer) == 0:
        return 0
    for item in split_answer:
        if item in split_question:
            match_count += 1
    return match_count / len(split_answer)

Initially, I had:

 if 'the' in split_answer:
        split_answer  = split_answer.remove('the')

Which resulted in:
TypeError: (“object of type ‘NoneType’ has no len()”, ‘occurred at index 5’)

Could someone show me a good resource to understand this better?

That’s the same code as the one you used above which you said works fine. What was the code that resulted in an error?

1 Like

Sorry I just changed it. This is the confusion I have related to the other question you answered of mine here:

So because it’s (split_answer) a list, I don’t reassign it back to itself?

That’s correct. remove() method for Python lists operates in-place. If you try to reassign it back to itself in this case, it ends up as None. That’s why you got the error for NoneType.

1 Like