Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving values but preserving order in a Python list [duplicate]

Tags:

python

list

I have a list

a=[1,2,3,4,5]

and want to 'move' its values so it changes into

a=[2,3,4,5,1]

and the next step

a=[3,4,5,1,2]

Is there a built-in function in Python to do that?

Or is there a shorter or nicer way than

b=[a[-1]]; b.extend(a[:-1]); a=b
like image 691
sloth Avatar asked Jul 31 '09 11:07

sloth


People also ask

How do you remove duplicate values from a list while preserving the order?

If you want to preserve the order while you remove duplicate elements from List in Python, you can use the OrderedDict class from the collections module. More specifically, we can use OrderedDict. fromkeys(list) to obtain a dictionary having duplicate elements removed, while still maintaining order.

How will you remove duplicates without changing the order?

To remove duplicates from a Python list while preserving the order of the elements, use the code list(dict. fromkeys(list)) that goes through two phases: (1) Convert the list to a dict using the dict. fromkeys() function with the list elements as keys and None as dict values.

Can list store duplicate values in Python?

Python list can contain duplicate elements.

How do you prevent duplicates in a list Python?

Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.


1 Answers

>>> a = [1,2,3,4,5]
>>> a.append(a.pop(0))
>>> a
[2, 3, 4, 5, 1]

This is expensive, though, as it has to shift the contents of the entire list, which is O(n). A better choice may be to use collections.deque if it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:

>>> a = collections.deque([1,2,3,4,5])
>>> a
deque([1, 2, 3, 4, 5])
>>> a.rotate(-1)
>>> a
deque([2, 3, 4, 5, 1])

Note also that both these solutions involve changing the original sequence object, whereas yours creates a new list and assigns it to a. So if we did:

>>> c = a
>>> # rotate a

With your method, c would continue to refer to the original, unrotated list, and with my methods, it will refer to the updated, rotated list/deque.

like image 77
Miles Avatar answered Oct 15 '22 11:10

Miles