Techno Blender
Digitally Yours.

How To Reverse Python Lists More Efficiently

0 47


Efficient reversal of lists in Python

Photo by 愚木混株 cdd20 on Unsplash

Lists are among the fundamental and most commonly used data structures in Python. A list is a mutable and ordered collection of objects that can also store duplicate values. They can even be used as queues and stacks (even though deque might be more efficient).

List reversal is a fairly common task performed by developers when writing Python applications. In today’s short tutorial we will demonstrate a few different ways for reversing a list and also discuss which approach performs better, especially when working with lists consisting of large volumes of data.

Using slicing with negative step size

Now let’s assume we have the following list consisting of some numerical values:

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]

We can reverse the list using slicing and a step size of 1.

>>> my_lst_reversed = my_lst[::-1]
>>> my_lst_reversed
[80, 100, 40, 25, 30, 0, 10]

The [::-1] notation essentially does two things:

  • It selects all the elements of the list (the first : )
  • It specifies a negative step size of 1, which means that the element are retrieved in the reversed order (from end to start)

If you would like to understand more about slicing and indexing in Python, you can refer to one of my previous articles, here on Medium.

Note that this approach looks like more Pythonic, but it should only be used when you would like to create a copy of the original list such that it contains the elements in reversed order.

If you would like to reverse a list in-place (or iterate over the elements of a reversed list), then there are a couple of other alternatives that are much more efficient than slicing with a negative step size.

Using list.reverse() method

If you are looking into reversing the elements of a list in-place (meaning that you don’t actually want to create another copy of the original list) then list.reverse() method is the most efficient way to do so.

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]
>>> my_lst.reverse()
>>> my_lst
[80, 100, 40, 25, 30, 0, 10]

Note that since the reverse() method happens in-place, we don’t need to assign the result of the operation back to a variable. Apart from performance implications, I also find this approach a bit more readable and clearly indicates that the list is being reversed.

Using reversed() function

Finally, another alternative is the reversed() built-in function that returns a reverse Iterator.

Return a reverse iterator.

seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

This approach is recommended when it comes to performing backwards iteration over a list.

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]
>>> my_lst_reverse_iter = reversed(my_lst)
>>> my_lst_reverse_iter
<list_reverseiterator object at 0x10afcae20>

As you can see, the reversed() function returned an Iterator we can loop over it:

>>> for element in my_lst_reverse_iter:
... print(element)
...
80
100
40
25
30
0
10

Note that you could even convert the iterator into a list:

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]
>>> my_lst_reverse = list(reversed(my_lst))
>>> my_lst_reverse
[80, 100, 40, 25, 30, 0, 10]

But if this is your end goal then I would personally go for the list.reverse() approach.

Final Thoughts

In today’s short tutorial we demonstrated two different ways for reversing a list of objects in Python. More specifically, we showcased how to do so using slicing with step size, the reverse() method of list as well as the built-in reversed() Python method.

To summarise,

  • If you would like to reverse a list in-place, go for list.reverse()
  • If you want to create a copy of the list in reverse order go for slicing with a negative step size (i.e. [::-1])
  • If you would like to iterate over a reversed list, go for reversed() function

Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.

Related articles you may also like


Efficient reversal of lists in Python

Photo by 愚木混株 cdd20 on Unsplash

Lists are among the fundamental and most commonly used data structures in Python. A list is a mutable and ordered collection of objects that can also store duplicate values. They can even be used as queues and stacks (even though deque might be more efficient).

List reversal is a fairly common task performed by developers when writing Python applications. In today’s short tutorial we will demonstrate a few different ways for reversing a list and also discuss which approach performs better, especially when working with lists consisting of large volumes of data.

Using slicing with negative step size

Now let’s assume we have the following list consisting of some numerical values:

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]

We can reverse the list using slicing and a step size of 1.

>>> my_lst_reversed = my_lst[::-1]
>>> my_lst_reversed
[80, 100, 40, 25, 30, 0, 10]

The [::-1] notation essentially does two things:

  • It selects all the elements of the list (the first : )
  • It specifies a negative step size of 1, which means that the element are retrieved in the reversed order (from end to start)

If you would like to understand more about slicing and indexing in Python, you can refer to one of my previous articles, here on Medium.

Note that this approach looks like more Pythonic, but it should only be used when you would like to create a copy of the original list such that it contains the elements in reversed order.

If you would like to reverse a list in-place (or iterate over the elements of a reversed list), then there are a couple of other alternatives that are much more efficient than slicing with a negative step size.

Using list.reverse() method

If you are looking into reversing the elements of a list in-place (meaning that you don’t actually want to create another copy of the original list) then list.reverse() method is the most efficient way to do so.

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]
>>> my_lst.reverse()
>>> my_lst
[80, 100, 40, 25, 30, 0, 10]

Note that since the reverse() method happens in-place, we don’t need to assign the result of the operation back to a variable. Apart from performance implications, I also find this approach a bit more readable and clearly indicates that the list is being reversed.

Using reversed() function

Finally, another alternative is the reversed() built-in function that returns a reverse Iterator.

Return a reverse iterator.

seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

This approach is recommended when it comes to performing backwards iteration over a list.

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]
>>> my_lst_reverse_iter = reversed(my_lst)
>>> my_lst_reverse_iter
<list_reverseiterator object at 0x10afcae20>

As you can see, the reversed() function returned an Iterator we can loop over it:

>>> for element in my_lst_reverse_iter:
... print(element)
...
80
100
40
25
30
0
10

Note that you could even convert the iterator into a list:

>>> my_lst = [10, 0, 30, 25, 40, 100, 80]
>>> my_lst_reverse = list(reversed(my_lst))
>>> my_lst_reverse
[80, 100, 40, 25, 30, 0, 10]

But if this is your end goal then I would personally go for the list.reverse() approach.

Final Thoughts

In today’s short tutorial we demonstrated two different ways for reversing a list of objects in Python. More specifically, we showcased how to do so using slicing with step size, the reverse() method of list as well as the built-in reversed() Python method.

To summarise,

  • If you would like to reverse a list in-place, go for list.reverse()
  • If you want to create a copy of the list in reverse order go for slicing with a negative step size (i.e. [::-1])
  • If you would like to iterate over a reversed list, go for reversed() function

Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.

Related articles you may also like

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment