Search code examples
pythonarrayscountingskip

Python Start counting array of length x starting from second item and finishing on the first one


In Python I have an array of length x.

let array = [0, 1, 2, 3, 4, 5]

I want to get from the array above the result like this: [1, 2, 3, 4, 5, 0]

So basically i wan't to skip the first term and loop it after the array ends and stop on the last skipped term. I'm pretty new to python, so couldn't figure it out on on my own + googling didn't help.

Help please, Much appreciated!


Solution

  • Use slicing and append().

    lst = [0, 1, 2, 3, 4, 5]
    new_lst = lst[1:]
    new_lst.append(lst[0])
    

    You could also use new_lst.extend(lst[:1]), though when the head slice is a single element, append(lst[0]) is probably slightly more efficient, since you don't have to construct another temporary list just to wrap a single value. lst[1:] + list[:1] is probably the worst though, since it has to create yet another throw away list object compared to the extend() version.