Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reorder a list? [closed]

Tags:

python

People also ask

How do you move an item to the front of a list in Python?

Method #2 : Using insert() + pop() This functionality can also be achieved using the inbuilt functions of python viz. insert() and pop() . The pop function returns the last element and that is inserted at front using the insert function.

How do you reorder items in a list Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do you sort a list without altering the content of the original list?

If you want to create a new sorted list without modifying the original one, you should use the sorted function instead. As you can notice, both sort and sorted sort items in an ascending order by default.

Can we rearrange list in Python?

Python provides two list methods to rearrange the order of the elements. Both methods mutate (change) the original list.


You can do it like this

mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist)         # prints: ['d', 'c', 'a', 'b', 'e']

>>> a = [1, 2, 3]
>>> a[0], a[2] = a[2], a[0]
>>> a
[3, 2, 1]

>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]

Is the final order defined by a list of indices ?

>>> items = [1, None, "chicken", int]
>>> order = [3, 0, 1, 2]

>>> ordered_list = [items[i] for i in order]
>>> ordered_list
[<type 'int'>, 1, None, 'chicken']

edit: meh. AJ was faster... How can I reorder a list in python?