Python Forum
Stuck on python quiz challenge - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Stuck on python quiz challenge (/thread-29044.html)



Stuck on python quiz challenge - baesian - Aug-15-2020

Hi Y'all.

I have recently purchased a book so I can teach my-self python. I'm just stick on one of the quizzes and need some guidance if possible. The question is :

Can you create a list l that prints [[1,2,3],[1,2,3]] but when I rotate only the first part by rotateRx(l[1]) and then print l it turns out that both parts have been rotated, i.e I get [[3,1,2],[3,1,2]].


I have tried to reproduce the output but only been able to rotate the second half. A bit baffled how you would rotate both. Any help would be appreciated.

My solution:

l=[[1,2,3],[1,2,3]]
def rotateRx4(alist):
         alist[0],alist[1],alist[2]=alist[-1],alist[0],alist[1]

    
rotateRx4(l[1])
print(l)



RE: Stuck on python quiz challenge - bowlofred - Aug-15-2020

Your question seems a bit scattered. There's no mention of rotation in your question, but then you say some part of it isn't working.

But the second sublist is rotated because that's the one that is fed to the rotation function.

l is [[1,2,3],[1,2,3]]
l[1] is the second element: [1,2,3]

You rotate (only) the second one because of line 6:
rotateRx4(l[1])



RE: Stuck on python quiz challenge - scidam - Aug-16-2020

If I understood you right, you want to apply rotation to the one part of a list and get rotated both parts of it.

inner_list = [1, 2, 3]
l = [inner_list, inner_list]
rotateRx4(l[1])
# now both sublists are rotated...
This is because lists are mutable in Python and the list l consist of two refs pointing to the same list. So, if you change one of them, the second will change too.