How do I move an element in my list to the end in python

>>> lst = ['string1', 'string2', 'string3']
>>> lst.append(lst.pop(lst.index('string2')))
>>> lst
['string1', 'string3', 'string2']

We look for the index of 'string2', pop that index out of the list and then append it to the list.

Perhaps a somewhat more exception free way is to add the thing you're looking for to the end of the list first (after all, you already presumably know what it is). Then delete the first instance of that string from the list:

>>> lst = ['string1', 'string2', 'string3']
>>> lst.append('string2')
>>> del lst[lst.index('string2')]  # Equivalent to lst.remove('string2')
>>> lst
['string1', 'string3', 'string2']

lst = ['string1', 'string2', 'string3']
lst.append('string2')
lst.remove('string2')     # -> ['string1', 'string3', 'string2']

(mgilson made an excellent point - if you add the value to the list first, there will always be one to remove)


sort is O(n) for this operation, so it's the same time complexity as the other answer without the 2 or 3 function lookups. There is no error if 'string2' isn't in the list

>>> lst = ['string1', 'string2', 'string3']
>>> lst.sort(key='string2'.__eq__)
>>> lst
['string1', 'string3', 'string2']

You can use this same trick to move all the "string2" to the end of the list. Or more generally an entire category eg to move everything starting with string to the end of the list:

lst.sort(key=lambda s:s.startswith('string'))

† Timsort sees this as a maximim of 3 "runs" and timsort is a stable sort

Tags:

Python

List