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
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.
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.
Python list can contain duplicate elements.
Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With