1

I want to write a function that moves the position of all elements in a list one position backwards (to the left). The only conditions are that the function should not mutate the original list, and it must return nothing. In essence, how do I go from the code I have created here:

def cycle(input_list):
   move = input_list
   move.append(move.pop(0))

...which moves every element one position backwards but mutates the original list, to one that does the same thing, but instead doesn't mutate the original list?

  • its not clear to me...you want to keep the original list as it is or not? – Netwave Mar 16 '16 at 08:18
  • I want to return a list that contains all the elements of the input_list, except each element is shifted one position backward. For example: def cycle([1, 2, 3, 4, 5]) Would return: [2, 3, 4, 5, 1] – Indifferent Potato Mar 16 '16 at 08:21
  • So why does your question say "it must return nothing"? That's a bit confusing! – PM 2Ring Mar 16 '16 at 08:38

2 Answers2

2

Easy task then, return a copy with the elements shifted:

def cycle(input_list):
    return input_list[1:] + input_list[:1]
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 2
    It will raise error as `input_list[1:]` is a list and `input_list[0]` is an item. Plus you don't need to check for length just do `def cycle(input_list): return input_list[1:] + input_list[:1]`. – Muhammad Tahir Mar 16 '16 at 08:33
  • @MuhammadTahir, true :), I cant just tested it – Netwave Mar 16 '16 at 08:35
0

You need to make a copy of input list, modify in and return the value from cycle function, i.e. like this:

  def cycle(input):
      if len(input) > 1:     # check for empty lists
          res = list(input)  # make actual copy of the list
          res.append(res.pop(0))
          return res
      else:
          return []

There's good post on copying lists in Python: How to clone or copy a list?

Community
  • 1
  • 1