Cycling values of a list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
6
down vote

favorite












I'm new to coding and am trying to write a simple code that will take a list, say [1,2,3] and cycle the elements n number of times. So if n=1, I should get A=[3,1,2]. If n=2, I should get A=[2,3,1].The code I have written is:



n=1
j=0
A = [1,2,3]
B = [None]*len(A)

while j<=n:
for i in range(0,len(A)):
B[i] = A[-1+i]
j=j+1
print(B)


The problem is that no matter what the value of n is I get the same answer which is only cycled once. I think the problem is that the loop is cycling through the same B every time, so I need to store the new B as something else and then repeat the loop with new B. But I can't figure out how to do that. Any tips would be appreciated










share|improve this question









New contributor




DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.























    up vote
    6
    down vote

    favorite












    I'm new to coding and am trying to write a simple code that will take a list, say [1,2,3] and cycle the elements n number of times. So if n=1, I should get A=[3,1,2]. If n=2, I should get A=[2,3,1].The code I have written is:



    n=1
    j=0
    A = [1,2,3]
    B = [None]*len(A)

    while j<=n:
    for i in range(0,len(A)):
    B[i] = A[-1+i]
    j=j+1
    print(B)


    The problem is that no matter what the value of n is I get the same answer which is only cycled once. I think the problem is that the loop is cycling through the same B every time, so I need to store the new B as something else and then repeat the loop with new B. But I can't figure out how to do that. Any tips would be appreciated










    share|improve this question









    New contributor




    DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





















      up vote
      6
      down vote

      favorite









      up vote
      6
      down vote

      favorite











      I'm new to coding and am trying to write a simple code that will take a list, say [1,2,3] and cycle the elements n number of times. So if n=1, I should get A=[3,1,2]. If n=2, I should get A=[2,3,1].The code I have written is:



      n=1
      j=0
      A = [1,2,3]
      B = [None]*len(A)

      while j<=n:
      for i in range(0,len(A)):
      B[i] = A[-1+i]
      j=j+1
      print(B)


      The problem is that no matter what the value of n is I get the same answer which is only cycled once. I think the problem is that the loop is cycling through the same B every time, so I need to store the new B as something else and then repeat the loop with new B. But I can't figure out how to do that. Any tips would be appreciated










      share|improve this question









      New contributor




      DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I'm new to coding and am trying to write a simple code that will take a list, say [1,2,3] and cycle the elements n number of times. So if n=1, I should get A=[3,1,2]. If n=2, I should get A=[2,3,1].The code I have written is:



      n=1
      j=0
      A = [1,2,3]
      B = [None]*len(A)

      while j<=n:
      for i in range(0,len(A)):
      B[i] = A[-1+i]
      j=j+1
      print(B)


      The problem is that no matter what the value of n is I get the same answer which is only cycled once. I think the problem is that the loop is cycling through the same B every time, so I need to store the new B as something else and then repeat the loop with new B. But I can't figure out how to do that. Any tips would be appreciated







      python python-3.x list for-loop






      share|improve this question









      New contributor




      DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 29 mins ago









      martineau

      62.7k887167




      62.7k887167






      New contributor




      DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 2 hours ago









      DeathbyGreen

      333




      333




      New contributor




      DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      DeathbyGreen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          6 Answers
          6






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          I think you're overcomplicating it. Consider changing it to something like the following:



          n = 1
          A = [1,2,3]
          B = A.copy()

          for _ in range(n):
          # Cycle through by concatenating the last element and all other elements together
          B = [B[-1]]+B[0:-1]

          print(B)


          In case of n=1, you get [3, 1, 2], and n=2 gives you [2, 3, 1]



          Note that what you are trying to do is implemented in numpy.roll (I suppose you're asking about the process, not the result, but just in case)



          import numpy as np

          >>> np.roll(A,1)
          array([3, 1, 2])
          >>> np.roll(A,2)
          array([2, 3, 1])





          share|improve this answer



























            up vote
            2
            down vote













            A simpler function for this is:



            def roll(L, n):
            n %= len(L)
            return L[-n:] + L[:-n]

            A = [1,2,3]
            roll(A, 1) # [3, 1, 2]
            roll(A, 2) # [2, 3, 1]
            roll(A, 3) # [1, 2, 3]
            roll(A, 4) # [3, 1, 2]


            Taking the modulus (n %= len(L)) avoids the need to keep cycling through. We then just concatenate an appropriate-sized slice off the end of the list to the beginning of it.






            share|improve this answer





























              up vote
              0
              down vote













              @sacul's answer works, but you were close! You missed updating A for the next iteration of the while loop after you created your new B.



              n=1
              j=0
              A = [1,2,3]
              B = [None]*len(A)

              while j<=n:
              for i in range(0,len(A)):
              B[i] = A[-1+i]
              A = B[:] # update A so that next time B works on the new A
              print('A is now ', A) # to debug
              j=j+1

              print(B)


              This results in the following print statements:



              A is now [3, 1, 2] 
              A is now [2, 3, 1]
              [2, 3, 1] # this is what finally B is





              share|improve this answer




















              • But this is the wrong outcome for n = 1... set while j<n instead.
                – Stuart
                29 mins ago










              • @Stuart What do you mean "wrong"? j = 1 can mean 2 iterations; it's just a matter of definition. This is OP's original code only modified slightly to explain where they went wrong.
                – slider
                17 mins ago










              • Wrong in the sense that it does not provide the output specified by the OP for the given A and n.
                – Stuart
                14 mins ago

















              up vote
              0
              down vote













              An itertools based solution



              from itertools import cycle, islice

              def roll(x, n):
              start = len(x) - n
              return islice(cycle(x), start, start + len(x))


              If we cycle through the values in x (we'd actually only do this at most twice). Then slice it so that it begins at the element we want and includes the correct number of elements.



              It's probably a little more esoteric than some of the other solutions, but worth throwing into the bag, given there are so many alternatives.



              itertools.islice returns a generator. If you wanted to print the result you'd need to convert it to list.






              share|improve this answer



























                up vote
                0
                down vote













                See @sacul's answer for the problem with your code. But list is not the most appropriate structure for such a requirement as each shift has O(n) complexity.



                deque ("double-ended qeueue") from the collections module provides this feature via its rotate method. This method works in-place and has O(k) complexity, where k is argument representing the number of rotations. Here's an example:



                from collections import deque

                d = deque([1,2,3])
                d.rotate(2)

                print(d)

                deque([2, 3, 1])





                share|improve this answer



























                  up vote
                  -1
                  down vote













                  Not going to in depth since someone already answered your question.. But an important property to note here is also that



                  A = [1, 2, 3] #Assuming that the length of the matrix you want to rotate is of length 3

                  If you want to cycle/rotate by 3, then you want to actually cycle/rotate by `len(A)%3` = 0
                  If you want to cycle/rotate by 6, then you want to actually cycle/rotate by `len(A)%6` = 0
                  If you want to cycle/rotate by 4, then you want to actually cycle/rotate by `len(A)%3` = 1
                  If you want to cycle/rotate by a number lesser than the length itself.. then just rotate it by that number!

                  so if you want to cycle by 2, then well.. rotate it by two..





                  share|improve this answer




















                  • Okay.. Why am I getting this downvote?
                    – Abhishek
                    4 mins ago










                  Your Answer





                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  convertImagesToLinks: true,
                  noModals: false,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );






                  DeathbyGreen is a new contributor. Be nice, and check out our Code of Conduct.









                   

                  draft saved


                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52674598%2fcycling-values-of-a-list%23new-answer', 'question_page');

                  );

                  Post as a guest






























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes








                  up vote
                  4
                  down vote



                  accepted










                  I think you're overcomplicating it. Consider changing it to something like the following:



                  n = 1
                  A = [1,2,3]
                  B = A.copy()

                  for _ in range(n):
                  # Cycle through by concatenating the last element and all other elements together
                  B = [B[-1]]+B[0:-1]

                  print(B)


                  In case of n=1, you get [3, 1, 2], and n=2 gives you [2, 3, 1]



                  Note that what you are trying to do is implemented in numpy.roll (I suppose you're asking about the process, not the result, but just in case)



                  import numpy as np

                  >>> np.roll(A,1)
                  array([3, 1, 2])
                  >>> np.roll(A,2)
                  array([2, 3, 1])





                  share|improve this answer
























                    up vote
                    4
                    down vote



                    accepted










                    I think you're overcomplicating it. Consider changing it to something like the following:



                    n = 1
                    A = [1,2,3]
                    B = A.copy()

                    for _ in range(n):
                    # Cycle through by concatenating the last element and all other elements together
                    B = [B[-1]]+B[0:-1]

                    print(B)


                    In case of n=1, you get [3, 1, 2], and n=2 gives you [2, 3, 1]



                    Note that what you are trying to do is implemented in numpy.roll (I suppose you're asking about the process, not the result, but just in case)



                    import numpy as np

                    >>> np.roll(A,1)
                    array([3, 1, 2])
                    >>> np.roll(A,2)
                    array([2, 3, 1])





                    share|improve this answer






















                      up vote
                      4
                      down vote



                      accepted







                      up vote
                      4
                      down vote



                      accepted






                      I think you're overcomplicating it. Consider changing it to something like the following:



                      n = 1
                      A = [1,2,3]
                      B = A.copy()

                      for _ in range(n):
                      # Cycle through by concatenating the last element and all other elements together
                      B = [B[-1]]+B[0:-1]

                      print(B)


                      In case of n=1, you get [3, 1, 2], and n=2 gives you [2, 3, 1]



                      Note that what you are trying to do is implemented in numpy.roll (I suppose you're asking about the process, not the result, but just in case)



                      import numpy as np

                      >>> np.roll(A,1)
                      array([3, 1, 2])
                      >>> np.roll(A,2)
                      array([2, 3, 1])





                      share|improve this answer












                      I think you're overcomplicating it. Consider changing it to something like the following:



                      n = 1
                      A = [1,2,3]
                      B = A.copy()

                      for _ in range(n):
                      # Cycle through by concatenating the last element and all other elements together
                      B = [B[-1]]+B[0:-1]

                      print(B)


                      In case of n=1, you get [3, 1, 2], and n=2 gives you [2, 3, 1]



                      Note that what you are trying to do is implemented in numpy.roll (I suppose you're asking about the process, not the result, but just in case)



                      import numpy as np

                      >>> np.roll(A,1)
                      array([3, 1, 2])
                      >>> np.roll(A,2)
                      array([2, 3, 1])






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 2 hours ago









                      sacul

                      21k31434




                      21k31434






















                          up vote
                          2
                          down vote













                          A simpler function for this is:



                          def roll(L, n):
                          n %= len(L)
                          return L[-n:] + L[:-n]

                          A = [1,2,3]
                          roll(A, 1) # [3, 1, 2]
                          roll(A, 2) # [2, 3, 1]
                          roll(A, 3) # [1, 2, 3]
                          roll(A, 4) # [3, 1, 2]


                          Taking the modulus (n %= len(L)) avoids the need to keep cycling through. We then just concatenate an appropriate-sized slice off the end of the list to the beginning of it.






                          share|improve this answer


























                            up vote
                            2
                            down vote













                            A simpler function for this is:



                            def roll(L, n):
                            n %= len(L)
                            return L[-n:] + L[:-n]

                            A = [1,2,3]
                            roll(A, 1) # [3, 1, 2]
                            roll(A, 2) # [2, 3, 1]
                            roll(A, 3) # [1, 2, 3]
                            roll(A, 4) # [3, 1, 2]


                            Taking the modulus (n %= len(L)) avoids the need to keep cycling through. We then just concatenate an appropriate-sized slice off the end of the list to the beginning of it.






                            share|improve this answer
























                              up vote
                              2
                              down vote










                              up vote
                              2
                              down vote









                              A simpler function for this is:



                              def roll(L, n):
                              n %= len(L)
                              return L[-n:] + L[:-n]

                              A = [1,2,3]
                              roll(A, 1) # [3, 1, 2]
                              roll(A, 2) # [2, 3, 1]
                              roll(A, 3) # [1, 2, 3]
                              roll(A, 4) # [3, 1, 2]


                              Taking the modulus (n %= len(L)) avoids the need to keep cycling through. We then just concatenate an appropriate-sized slice off the end of the list to the beginning of it.






                              share|improve this answer














                              A simpler function for this is:



                              def roll(L, n):
                              n %= len(L)
                              return L[-n:] + L[:-n]

                              A = [1,2,3]
                              roll(A, 1) # [3, 1, 2]
                              roll(A, 2) # [2, 3, 1]
                              roll(A, 3) # [1, 2, 3]
                              roll(A, 4) # [3, 1, 2]


                              Taking the modulus (n %= len(L)) avoids the need to keep cycling through. We then just concatenate an appropriate-sized slice off the end of the list to the beginning of it.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited 52 mins ago

























                              answered 58 mins ago









                              Stuart

                              5,07811122




                              5,07811122




















                                  up vote
                                  0
                                  down vote













                                  @sacul's answer works, but you were close! You missed updating A for the next iteration of the while loop after you created your new B.



                                  n=1
                                  j=0
                                  A = [1,2,3]
                                  B = [None]*len(A)

                                  while j<=n:
                                  for i in range(0,len(A)):
                                  B[i] = A[-1+i]
                                  A = B[:] # update A so that next time B works on the new A
                                  print('A is now ', A) # to debug
                                  j=j+1

                                  print(B)


                                  This results in the following print statements:



                                  A is now [3, 1, 2] 
                                  A is now [2, 3, 1]
                                  [2, 3, 1] # this is what finally B is





                                  share|improve this answer




















                                  • But this is the wrong outcome for n = 1... set while j<n instead.
                                    – Stuart
                                    29 mins ago










                                  • @Stuart What do you mean "wrong"? j = 1 can mean 2 iterations; it's just a matter of definition. This is OP's original code only modified slightly to explain where they went wrong.
                                    – slider
                                    17 mins ago










                                  • Wrong in the sense that it does not provide the output specified by the OP for the given A and n.
                                    – Stuart
                                    14 mins ago














                                  up vote
                                  0
                                  down vote













                                  @sacul's answer works, but you were close! You missed updating A for the next iteration of the while loop after you created your new B.



                                  n=1
                                  j=0
                                  A = [1,2,3]
                                  B = [None]*len(A)

                                  while j<=n:
                                  for i in range(0,len(A)):
                                  B[i] = A[-1+i]
                                  A = B[:] # update A so that next time B works on the new A
                                  print('A is now ', A) # to debug
                                  j=j+1

                                  print(B)


                                  This results in the following print statements:



                                  A is now [3, 1, 2] 
                                  A is now [2, 3, 1]
                                  [2, 3, 1] # this is what finally B is





                                  share|improve this answer




















                                  • But this is the wrong outcome for n = 1... set while j<n instead.
                                    – Stuart
                                    29 mins ago










                                  • @Stuart What do you mean "wrong"? j = 1 can mean 2 iterations; it's just a matter of definition. This is OP's original code only modified slightly to explain where they went wrong.
                                    – slider
                                    17 mins ago










                                  • Wrong in the sense that it does not provide the output specified by the OP for the given A and n.
                                    – Stuart
                                    14 mins ago












                                  up vote
                                  0
                                  down vote










                                  up vote
                                  0
                                  down vote









                                  @sacul's answer works, but you were close! You missed updating A for the next iteration of the while loop after you created your new B.



                                  n=1
                                  j=0
                                  A = [1,2,3]
                                  B = [None]*len(A)

                                  while j<=n:
                                  for i in range(0,len(A)):
                                  B[i] = A[-1+i]
                                  A = B[:] # update A so that next time B works on the new A
                                  print('A is now ', A) # to debug
                                  j=j+1

                                  print(B)


                                  This results in the following print statements:



                                  A is now [3, 1, 2] 
                                  A is now [2, 3, 1]
                                  [2, 3, 1] # this is what finally B is





                                  share|improve this answer












                                  @sacul's answer works, but you were close! You missed updating A for the next iteration of the while loop after you created your new B.



                                  n=1
                                  j=0
                                  A = [1,2,3]
                                  B = [None]*len(A)

                                  while j<=n:
                                  for i in range(0,len(A)):
                                  B[i] = A[-1+i]
                                  A = B[:] # update A so that next time B works on the new A
                                  print('A is now ', A) # to debug
                                  j=j+1

                                  print(B)


                                  This results in the following print statements:



                                  A is now [3, 1, 2] 
                                  A is now [2, 3, 1]
                                  [2, 3, 1] # this is what finally B is






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered 1 hour ago









                                  slider

                                  2,210925




                                  2,210925











                                  • But this is the wrong outcome for n = 1... set while j<n instead.
                                    – Stuart
                                    29 mins ago










                                  • @Stuart What do you mean "wrong"? j = 1 can mean 2 iterations; it's just a matter of definition. This is OP's original code only modified slightly to explain where they went wrong.
                                    – slider
                                    17 mins ago










                                  • Wrong in the sense that it does not provide the output specified by the OP for the given A and n.
                                    – Stuart
                                    14 mins ago
















                                  • But this is the wrong outcome for n = 1... set while j<n instead.
                                    – Stuart
                                    29 mins ago










                                  • @Stuart What do you mean "wrong"? j = 1 can mean 2 iterations; it's just a matter of definition. This is OP's original code only modified slightly to explain where they went wrong.
                                    – slider
                                    17 mins ago










                                  • Wrong in the sense that it does not provide the output specified by the OP for the given A and n.
                                    – Stuart
                                    14 mins ago















                                  But this is the wrong outcome for n = 1... set while j<n instead.
                                  – Stuart
                                  29 mins ago




                                  But this is the wrong outcome for n = 1... set while j<n instead.
                                  – Stuart
                                  29 mins ago












                                  @Stuart What do you mean "wrong"? j = 1 can mean 2 iterations; it's just a matter of definition. This is OP's original code only modified slightly to explain where they went wrong.
                                  – slider
                                  17 mins ago




                                  @Stuart What do you mean "wrong"? j = 1 can mean 2 iterations; it's just a matter of definition. This is OP's original code only modified slightly to explain where they went wrong.
                                  – slider
                                  17 mins ago












                                  Wrong in the sense that it does not provide the output specified by the OP for the given A and n.
                                  – Stuart
                                  14 mins ago




                                  Wrong in the sense that it does not provide the output specified by the OP for the given A and n.
                                  – Stuart
                                  14 mins ago










                                  up vote
                                  0
                                  down vote













                                  An itertools based solution



                                  from itertools import cycle, islice

                                  def roll(x, n):
                                  start = len(x) - n
                                  return islice(cycle(x), start, start + len(x))


                                  If we cycle through the values in x (we'd actually only do this at most twice). Then slice it so that it begins at the element we want and includes the correct number of elements.



                                  It's probably a little more esoteric than some of the other solutions, but worth throwing into the bag, given there are so many alternatives.



                                  itertools.islice returns a generator. If you wanted to print the result you'd need to convert it to list.






                                  share|improve this answer
























                                    up vote
                                    0
                                    down vote













                                    An itertools based solution



                                    from itertools import cycle, islice

                                    def roll(x, n):
                                    start = len(x) - n
                                    return islice(cycle(x), start, start + len(x))


                                    If we cycle through the values in x (we'd actually only do this at most twice). Then slice it so that it begins at the element we want and includes the correct number of elements.



                                    It's probably a little more esoteric than some of the other solutions, but worth throwing into the bag, given there are so many alternatives.



                                    itertools.islice returns a generator. If you wanted to print the result you'd need to convert it to list.






                                    share|improve this answer






















                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      An itertools based solution



                                      from itertools import cycle, islice

                                      def roll(x, n):
                                      start = len(x) - n
                                      return islice(cycle(x), start, start + len(x))


                                      If we cycle through the values in x (we'd actually only do this at most twice). Then slice it so that it begins at the element we want and includes the correct number of elements.



                                      It's probably a little more esoteric than some of the other solutions, but worth throwing into the bag, given there are so many alternatives.



                                      itertools.islice returns a generator. If you wanted to print the result you'd need to convert it to list.






                                      share|improve this answer












                                      An itertools based solution



                                      from itertools import cycle, islice

                                      def roll(x, n):
                                      start = len(x) - n
                                      return islice(cycle(x), start, start + len(x))


                                      If we cycle through the values in x (we'd actually only do this at most twice). Then slice it so that it begins at the element we want and includes the correct number of elements.



                                      It's probably a little more esoteric than some of the other solutions, but worth throwing into the bag, given there are so many alternatives.



                                      itertools.islice returns a generator. If you wanted to print the result you'd need to convert it to list.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 19 mins ago









                                      Paul Rooney

                                      12.1k62642




                                      12.1k62642




















                                          up vote
                                          0
                                          down vote













                                          See @sacul's answer for the problem with your code. But list is not the most appropriate structure for such a requirement as each shift has O(n) complexity.



                                          deque ("double-ended qeueue") from the collections module provides this feature via its rotate method. This method works in-place and has O(k) complexity, where k is argument representing the number of rotations. Here's an example:



                                          from collections import deque

                                          d = deque([1,2,3])
                                          d.rotate(2)

                                          print(d)

                                          deque([2, 3, 1])





                                          share|improve this answer
























                                            up vote
                                            0
                                            down vote













                                            See @sacul's answer for the problem with your code. But list is not the most appropriate structure for such a requirement as each shift has O(n) complexity.



                                            deque ("double-ended qeueue") from the collections module provides this feature via its rotate method. This method works in-place and has O(k) complexity, where k is argument representing the number of rotations. Here's an example:



                                            from collections import deque

                                            d = deque([1,2,3])
                                            d.rotate(2)

                                            print(d)

                                            deque([2, 3, 1])





                                            share|improve this answer






















                                              up vote
                                              0
                                              down vote










                                              up vote
                                              0
                                              down vote









                                              See @sacul's answer for the problem with your code. But list is not the most appropriate structure for such a requirement as each shift has O(n) complexity.



                                              deque ("double-ended qeueue") from the collections module provides this feature via its rotate method. This method works in-place and has O(k) complexity, where k is argument representing the number of rotations. Here's an example:



                                              from collections import deque

                                              d = deque([1,2,3])
                                              d.rotate(2)

                                              print(d)

                                              deque([2, 3, 1])





                                              share|improve this answer












                                              See @sacul's answer for the problem with your code. But list is not the most appropriate structure for such a requirement as each shift has O(n) complexity.



                                              deque ("double-ended qeueue") from the collections module provides this feature via its rotate method. This method works in-place and has O(k) complexity, where k is argument representing the number of rotations. Here's an example:



                                              from collections import deque

                                              d = deque([1,2,3])
                                              d.rotate(2)

                                              print(d)

                                              deque([2, 3, 1])






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered 16 mins ago









                                              jpp

                                              69.2k174085




                                              69.2k174085




















                                                  up vote
                                                  -1
                                                  down vote













                                                  Not going to in depth since someone already answered your question.. But an important property to note here is also that



                                                  A = [1, 2, 3] #Assuming that the length of the matrix you want to rotate is of length 3

                                                  If you want to cycle/rotate by 3, then you want to actually cycle/rotate by `len(A)%3` = 0
                                                  If you want to cycle/rotate by 6, then you want to actually cycle/rotate by `len(A)%6` = 0
                                                  If you want to cycle/rotate by 4, then you want to actually cycle/rotate by `len(A)%3` = 1
                                                  If you want to cycle/rotate by a number lesser than the length itself.. then just rotate it by that number!

                                                  so if you want to cycle by 2, then well.. rotate it by two..





                                                  share|improve this answer




















                                                  • Okay.. Why am I getting this downvote?
                                                    – Abhishek
                                                    4 mins ago














                                                  up vote
                                                  -1
                                                  down vote













                                                  Not going to in depth since someone already answered your question.. But an important property to note here is also that



                                                  A = [1, 2, 3] #Assuming that the length of the matrix you want to rotate is of length 3

                                                  If you want to cycle/rotate by 3, then you want to actually cycle/rotate by `len(A)%3` = 0
                                                  If you want to cycle/rotate by 6, then you want to actually cycle/rotate by `len(A)%6` = 0
                                                  If you want to cycle/rotate by 4, then you want to actually cycle/rotate by `len(A)%3` = 1
                                                  If you want to cycle/rotate by a number lesser than the length itself.. then just rotate it by that number!

                                                  so if you want to cycle by 2, then well.. rotate it by two..





                                                  share|improve this answer




















                                                  • Okay.. Why am I getting this downvote?
                                                    – Abhishek
                                                    4 mins ago












                                                  up vote
                                                  -1
                                                  down vote










                                                  up vote
                                                  -1
                                                  down vote









                                                  Not going to in depth since someone already answered your question.. But an important property to note here is also that



                                                  A = [1, 2, 3] #Assuming that the length of the matrix you want to rotate is of length 3

                                                  If you want to cycle/rotate by 3, then you want to actually cycle/rotate by `len(A)%3` = 0
                                                  If you want to cycle/rotate by 6, then you want to actually cycle/rotate by `len(A)%6` = 0
                                                  If you want to cycle/rotate by 4, then you want to actually cycle/rotate by `len(A)%3` = 1
                                                  If you want to cycle/rotate by a number lesser than the length itself.. then just rotate it by that number!

                                                  so if you want to cycle by 2, then well.. rotate it by two..





                                                  share|improve this answer












                                                  Not going to in depth since someone already answered your question.. But an important property to note here is also that



                                                  A = [1, 2, 3] #Assuming that the length of the matrix you want to rotate is of length 3

                                                  If you want to cycle/rotate by 3, then you want to actually cycle/rotate by `len(A)%3` = 0
                                                  If you want to cycle/rotate by 6, then you want to actually cycle/rotate by `len(A)%6` = 0
                                                  If you want to cycle/rotate by 4, then you want to actually cycle/rotate by `len(A)%3` = 1
                                                  If you want to cycle/rotate by a number lesser than the length itself.. then just rotate it by that number!

                                                  so if you want to cycle by 2, then well.. rotate it by two..






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered 1 hour ago









                                                  Abhishek

                                                  947219




                                                  947219











                                                  • Okay.. Why am I getting this downvote?
                                                    – Abhishek
                                                    4 mins ago
















                                                  • Okay.. Why am I getting this downvote?
                                                    – Abhishek
                                                    4 mins ago















                                                  Okay.. Why am I getting this downvote?
                                                  – Abhishek
                                                  4 mins ago




                                                  Okay.. Why am I getting this downvote?
                                                  – Abhishek
                                                  4 mins ago










                                                  DeathbyGreen is a new contributor. Be nice, and check out our Code of Conduct.









                                                   

                                                  draft saved


                                                  draft discarded


















                                                  DeathbyGreen is a new contributor. Be nice, and check out our Code of Conduct.












                                                  DeathbyGreen is a new contributor. Be nice, and check out our Code of Conduct.











                                                  DeathbyGreen is a new contributor. Be nice, and check out our Code of Conduct.













                                                   


                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52674598%2fcycling-values-of-a-list%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest













































































                                                  Comments

                                                  Popular posts from this blog

                                                  Long meetings (6-7 hours a day): Being “babysat” by supervisor

                                                  What does second last employer means? [closed]

                                                  One-line joke