I have a list of strings called values and I want to make an element in the list to be the very last element. For example, if I have the string:
['string1', 'string2', 'string3']
I want string2 to be the very last element:
['string1', 'string3', 'string2']
There also may be an instance when my list does not contain string2. Is there an easy way to do this? This is what I have so far:
if 'string2' in values: for i in values: #remove string2 and append to end
Method : Using pop() + insert() + index() This particular task can be performed using combination of above functions. In this we just use the property of pop function to return and remove element and insert it to the specific position of other list using index function.
If we want to add an element at the end of a list, we should use append . It is faster and direct. If we want to add an element somewhere within a list, we should use insert . It is the only option for this.
Method #2 : Using insert() + pop() insert() and pop() . The pop function returns the last element and that is inserted at front using the insert function.
>>> 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']
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
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