0
def double_reverse(words_list):
    reverse = []
    reverse1= []
    reverse = words_list[::-1] 
    
    for i in reverse:
        reverse1.append(i[::-1])
    words_list = reverse1

Hi there,

I have this question for a practice assessment:

Question

For this question, I cannot return or print anything. Instead, I need to update the words_list list value so that I can get the desired result.

However, for some reason I can only get the original list. Why is the list not being updated?

Cheers

chris
  • 11
  • 1
  • [this](https://stackoverflow.com/a/67363959/14429185) will help you. – nobleknight May 03 '21 at 07:04
  • Assigning to the `words_list` variable within `double_reverse` has no effect outside of that function. Instead, you need to modify the list that `words_list` references, modifying it in-place. That way, any other references to that list will see the changes. – Tom Karzes May 03 '21 at 07:04
  • Does this answer your question? [Why am I unable to return a list of words after I've reversed the order?](https://stackoverflow.com/questions/67363816/why-am-i-unable-to-return-a-list-of-words-after-ive-reversed-the-order) – Karun Ellango May 03 '21 at 07:04

1 Answers1

2
words_list = reverse1

just rebinds the local variable words_list. It does not mutate the object that this variable referenced before (the one that got passed in as a function argument). A simple fix would be slice assignment:

words_list[:] = reverse1

which constitutes a mutation on said object.

A general pythonic simplification of your function could be:

def double_reverse(words_list):
    words_list[:] = [w[::-1] for w in reversed(words_list)]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thanks very much, sorry for the naivety but what do you mean by rebind and mutate? – chris May 03 '21 at 07:12
  • There is plenty of material on that topic =) e.g. https://stackoverflow.com/questions/9073995/difference-between-mutation-rebinding-copying-value-and-assignment-operator or https://frecar.no/mutation-rebinding-python/ (or any other google result) – user2390182 May 03 '21 at 07:14