Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 272
DannyD Avatar asked Dec 02 '13 04:12

DannyD


People also ask

How do you move a list element in Python?

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.

How do you add an element to the end of a list?

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.

How do you move the last element of a list to the front in Python?

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.


2 Answers

>>> 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'] 
like image 108
mgilson Avatar answered Oct 26 '22 17:10

mgilson


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

like image 34
John La Rooy Avatar answered Oct 26 '22 16:10

John La Rooy