0

I need a specific function for a program of mine. It supposed to work something like this:

list = ['C','T', 'Z','L','P']
new_list = hypothetical_function('Z')
print(new_list)
#['Z','L','P','C','T']

Is there any built-in function in python to do this kind of operation on list?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ovi Paul
  • 9
  • 3
  • 3
    I think your hypothetical function ought to take the existing list as one of the arguments. – alani Aug 22 '20 at 22:19
  • Does this answer your question? [Simple syntax for bringing a list element to the front in python?](https://stackoverflow.com/questions/1014523/simple-syntax-for-bringing-a-list-element-to-the-front-in-python) – sguridirt Aug 22 '20 at 22:21
  • 1
    so, what's your question exactly? – AM Z Aug 22 '20 at 22:24
  • 2
    A couple of tips to help us help you: 1) be a bit more specific about your needs. You say it should work "something like this", and you give an example, but describe what you're showing in the example. 2) Show us some code that you've already tried to write, and how it failed. – captnsupremo Aug 22 '20 at 22:43

2 Answers2

2

Just obtain the position using index and then concatenate the relevant slices:

def reorder(lst, first):
    pos = lst.index(first)
    return lst[pos:] + lst[:pos]

lst = ['C','T', 'Z','L','P']
print(reorder(lst, 'Z'))

(I don't know of a built-in function that will do this.)

alani
  • 12,573
  • 2
  • 13
  • 23
  • 1
    Ha! I'd totally misread the question and didn't notice that OP was indexing on the element, not the number of rotations. This is the correct answer~ – Adam Smith Aug 22 '20 at 22:24
1

You can use the method rotate of the deque object:

from collections import deque

dq = deque(lst)
dq.rotate(lst.index('Z') + 1)
print(dq)
# deque(['Z', 'L', 'P', 'C', 'T'])
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73