1

I have an assignment in Python (using Jupyter).

Here it is:

enter image description here

I need to make a list called weird on the 27th line that should results [[3, 1, 2], [3, 1, 2]] if I do xrotateR(weird[0]) function on it.

How can I do this?

The xrotateR function is:

def xrotateR(lst) :
    c=lst[-1:]
    lst[:]=c+lst[0:-1]

Thanks!

merv
  • 67,214
  • 13
  • 180
  • 245
Graha Pramudita
  • 119
  • 2
  • 11

1 Answers1

2

They want you to put the same list (literally the same object in memory, not just equal lists) in a list of lists.

>>> def xrotateR(lst) :
...     c=lst[-1:]
...     lst[:]=c+lst[0:-1]
... 
>>> weird = [[1, 2, 3]]*2
>>> weird
[[1, 2, 3], [1, 2, 3]]

We can confirm that the elements of weird are not just equal but the same object with the is operator.

>>> weird[0] is weird[1]
True

Thus, xrotateR will mutate both entries of weird.

>>> xrotateR(weird[0])
>>> weird
[[3, 1, 2], [3, 1, 2]]

Instantiating such a list is a common bug, by the way.

edit: try out Python Tutor for the visualizations they ask, it will draw the correct diagrams for you. Just make sure you understand them. ;)

timgeb
  • 76,762
  • 20
  • 123
  • 145