2

I'm new to python and programming in general, so I feel like I'm trying to wrap my head around the simplest of things...

Let's say I have a list of 12 items:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 

and a variable that matches one of the items in the list:

b = 7 

Now I want to find that match in the list and move every item before the match to the end of the list in the same order like so:

a = [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6] 

How would I go about doing this in python 3.4.2?

The match could be for any item at any index, but the number of items will always be the same (12).

0

2 Answers 2

5

Use slicing of list:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> idx = a.index(7) >>> a = a[idx:] + a[:idx] >>> a [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6] 

Note that this will throw a ValueError if the value being searched is not found in the array, in which case you will need to capture it using try-except block

Sign up to request clarification or add additional context in comments.

1 Comment

Thank-you. I haven't really learned about .index() yet. I guess that's why I couldn't find a solution to my problem. 3 hours later and I've finished creating a small program that creates different musical chords depending on the key the music is in (defined by the user). :P Just for practice.
1

Another option is to simultaneously use append and pop:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> idx = a.index(7) >>> for _ in range(idx): ... a.append(a.pop(0)) >>> a [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6] 

I do not advocate using this over the slicing method because this will be very slow (lists are not optimized for poping from the front). I just mention it here to show another method that I believe is a little bit easier to understand at first glance.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.