Back to Browse

"Reverse a List in Python" Tutorial: Three Methods & How-to Demos

56.1K views
Jun 21, 2017
17:42

https://dbader.org/python-tricks ► Get practical Python tricks and snippets that will make you a more effective Pythonista In this Python tutorial video you'll see how to reverse a list in Python. There are 3 common implementations for a Python reverse list algorithm and we'll do a deep dive on all of them. Here's what we'll cover with overviews and hands on REPL demos: 1. Reversing Python lists in-place with the "list.reverse()" method. This is a great option to reverse the order of a list (or any sequence) in Python. It modifies the original object in-place which means no additional memory is required. However the downside is, of course, that the original list is changed. 2. Using a list slicing "trick" to create a reversed copy of a Python list. You can use Python's list slicing syntax to create a reversed copy of a list: `my_list[::-1]`. This works well, however it is slightly arcane and therefore not very Pythonic, in my opinion. 3. Using Python's built-in "reversed()" function to create a reverse iterator that we can then turn into a proper list object. This is a clean solution that uses some advanced Python features like iterators—but it's also very readable due to the naming of the "reversed" function. This is a great option if you're looking to reverse a for loop and you don't need a full copy of the original list. Note that there are other approaches like implementing list reversal from scratch or reversing a list using a recursive algorithm that are common interview questions but not very good solutions for Python programming in the "real world". Watch the full video for details and hands-on demos for each approach. At the end of the video you'll see my final verdict on which list reversal approach I recommend and why. FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube * * * ► Python MUGS, T-SHIRTS & MORE: https://nerdlettering.com FREE Python Tutorials & News: » Python Tutorials: https://dbader.org » Python News on Twitter: https://twitter.com/@dbader_org » Weekly Tips for Pythonistas: https://dbader.org/newsletter » Subscribe to this channel: https://dbader.org/youtube

Download

1 formats

Video Formats

360pmp418.0 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

"Reverse a List in Python" Tutorial: Three Methods & How-to Demos | NatokHD