Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create a "reversed" list in Python?

In Python, what is the best way to create a new list whose items are the same as those of some other list, but in reverse order? (I don't want to modify the existing list in place.)

Here is one solution that has occurred to me:

new_list = list(reversed(old_list)) 

It's also possible to duplicate old_list then reverse the duplicate in place:

new_list = list(old_list) # or `new_list = old_list[:]` new_list.reverse() 

Is there a better option that I've overlooked? If not, is there a compelling reason (such as efficiency) to use one of the above approaches over the other?

like image 769
davidchambers Avatar asked Sep 14 '10 02:09

davidchambers


People also ask

What is the easiest way to reverse a list in Python?

Python lists can be reversed in-place with the list. reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required.

How do you create a reverse list in Python?

Method 1: Reversing a list using the reversed() and reverse() built-in function. Using the reversed() method and reverse() method, we can reverse the contents of the list object in place i.e., we don't need to create a new list instead we just copy the existing elements to the original list in reverse order.

How do you reverse a list in a list Python?

Python provides a builtin function reversed() i.e. The reversed() function returned a reverse iterator of the given list and then we passed this reverse iterator to the list() function, which iterated over all the elements of the list in reverse order and inserted them to a new list i.e. a list with reversed contents.

How do you reverse a list without reverse Python?

In order to reverse a list without using the built-in reverse() function, we use the Slicing Operator. The slicing operator is another method used for reversing the data elements.


1 Answers

newlist = oldlist[::-1] 

The [::-1] slicing (which my wife Anna likes to call "the Martian smiley";-) means: slice the whole sequence, with a step of -1, i.e., in reverse. It works for all sequences.

Note that this (and the alternatives you mentioned) is equivalent to a "shallow copy", i.e.: if the items are mutable and you call mutators on them, the mutations in the items held in the original list are also in the items in the reversed list, and vice versa. If you need to avoid that, a copy.deepcopy (while always a potentially costly operation), followed in this case by a .reverse, is the only good option.

like image 146
Alex Martelli Avatar answered Sep 30 '22 17:09

Alex Martelli