datastructures-in-python
  • Home
  • Downloads & Misc-Assets
  • README
  • Navigation
  • Curriculum
    • Outline
      • General Content
      • Python-Data-Structures-Unit
    • wk17
      • Outline-w17
      • homework
      • D1-Module 01 - Python I
        • Configuring Ubuntu for Python Web Development
        • Install Python
      • D2- Module 02 - Python II
      • D3- Module 03 - Python III
      • D4-Module 04 - Python IV
    • wk18
      • Outline-W-18
      • D1- Module 01 - Number Bases and Character Encoding
      • D2- Module 02 - Hash Tables I
        • Hash Table / Hash Map In Python:
        • Hash Table Use Cases
        • Practice
      • D3-Module 03 - Hash Tables II
      • D4- Module 04 - Searching and Recursion
    • wk19
      • Outline-W-19
      • D1- Module 01 - Linked Lists
        • Homework
          • Helpful Resource
      • D2- Module 02 - Queues and Stacks
      • D3- Module 03 - Binary Search Trees
        • BST Definition:
      • D4- Module 04 - Tree Traversal
        • Tree Traversals (Inorder, Preorder and Postorder)
    • wk20
      • Outline-W-20
      • D1-Graphs I
      • D2-Graphs 2
      • DFS
      • D4
  • Utilities
    • Utilites
      • Python Libraries
      • YouTube
      • Code Lab Notebook Embeds From Lecture
    • Code lab Notebooks
    • Repl.IT
      • Trinket
  • Abstract Data Structures
    • Algorithms
      • Algo-Resources
        • List-Of-Solutions-To-Common-Interview-Questions
      • Dijkstra's algorithm
      • Calculate a Factorial With Python - Iterative and Recursive
      • DFS
      • BFS
        • BFS Examples
      • Palendrome
    • Data Structures Overview
      • General Data Structures Notes
        • DS-Explained-Simple
      • Untitled
      • Algorithms
      • Dictionary
    • Abstract Data Structures:
      • Array
        • Extra-Array
        • Array Practice
      • Binary Search
      • Binary Tree
        • Binary Tree Explained
        • Find the maximum path sum between two leaves of a binary tree
      • Binary Search Tree
        • BST Explained
        • BST Insert
        • BST-Largest-Sub-Tree
      • Exotic
        • Tire
        • Dynamic Programming
      • Graphs
        • Overflow Practice Problems
        • Graphs Explained
        • Earliest Ancestor
        • _Mini Graph-Projects
          • # Social Graph
          • number of 1 islands
          • Searching and Generating Graphs
        • Graph FAQ
          • Graph DFS
        • Connected Components
        • Randomness
        • Graph BFS
        • Topological Sort
      • Hash Table
        • Hashmap or Hash tables
        • Hash Table and HashMap in Python
      • Heap
        • Heap Examples
      • String
      • Map
        • Examples
      • Queue
        • Queue Continued...
        • Queue Sandbox
        • Dequeue
      • Tree
        • In Order Traversal
        • Tree Equal ?
        • Ternary-search-trees
        • Red_Black Tree
        • Tree Mirror:
        • Tree Traversal
      • Recursion
        • Recursion Explained
          • Recursion Examples
      • Linked List
        • Linked List Background
        • Double Linked List
        • List Example
        • Examples (LL) continued
        • List Operations
      • Set
        • Set
        • Set Intersection Union
        • Disjoint Set
      • Sorting
        • In JavaScript
        • Merge Sort
        • Iterative Sorting
        • Recursive Sorting
        • Graph Topological Sort
        • SelectionSort
        • Quick Sort
        • Merge Sort
        • Insertion Sort
      • Stack
        • Stack Continued
        • Stack Part 3
      • Searching
        • Binary Search
        • Searching & Sorting Computational Complexity (JS)
  • practice
    • GCA Sprint Prep:
      • Practice Problems
      • Code Signal CGA Sprint Resources
      • CGA-Sprint Prep
    • Supplemental Practice:
      • Practice
      • JavaScript Algorithms
      • Industry Standard Algorithms
        • Interview Practice Resources
        • Write a Program to Find the Maximum Depth or Height of a Tree
      • Random Examples
      • Prompts
      • JS_BASICS
  • Resources
    • Python Cheat Sheet
      • Cheatsheet-v2
      • List Of Python Cheat Sheets
    • Youtube
    • PDF Downloads
    • Intro 2 Python
    • Dictionaries
      • Dictionaries Continued
    • Python VS JavaScript
    • Misc. Resources
    • Things To Internalize:
      • Functions
    • Intro To Python w Jupyter Notebooks
    • Calculating Big O
    • Useful Links
      • Awesome Python
      • My-Links
      • Beginners Guide To Python
  • Docs
    • Docs
      • Strings
        • Strings Continued
      • Touple
      • Values Expressions & Statments
      • Dictionaries, sets, files, and modules
        • Modules
      • Built-in Types
      • Built In Functions
        • Zip Function
      • Functions
      • Classes and objects
        • Inheritance
        • Classes
          • Python Objects & Classes
          • index
      • Dictionaries
      • Conditionals and loops
      • Lists
        • Reverse A List
        • Python Data Structures
        • More On Lists
        • Examples
          • More-Examples
        • List Compehensions
      • Basic Syntax
      • String-Methods
    • Queue & Stacks
  • quick-reference
    • My Medium Articles
    • Free Python Books
    • WHY Python?
    • Debugging
    • Python Snippets
    • Python3 Regex
    • Python Module Index:
      • Requests Module
    • Creating Python Modules
    • Useful Info
    • Python Glossary
    • Python Snippets
  • MISC
    • Built-in Methods & Functions
    • Data Structures Types
    • Math
    • Unsorted Examples
    • Outline
    • About Python
      • Python VS JavaScript
      • Python Modules & Python Packages
      • Misc
      • Python's Default Argument Values and Lists
      • SCRAP
  • Interview Prep
    • Interview Resources
      • By Example
        • Algo-Prep
      • Permutation
      • How to Write an Effective Resume of Python Developer
      • Interview Checklist
      • 150 Practice Problems & Solutions
  • Installations Setup & Env
    • python-setup
    • Installing Python Modules
    • Set Up Virtual Enviornment
  • Aux-Exploration
    • Related Studies
      • Self-Organizing Maps: Theory and Implementation in Python with NumPy
      • List Directory Contents
      • Employee Manager
      • OS Module
      • server-side-scripting
      • Web Scraping
      • Reading and Writing to text files in Python
      • General Data Structures
      • Touple
      • How to round Python values to whole numbers?
      • Python Array Module
      • Data Structures In JavaScript
      • Dunder Methods
      • Python GitHub API
      • JS-Event Loop
      • JavaScript Event Loop
      • Manipulating Files & Folders
  • experiments
    • Untitled
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Docs
  2. Docs
  3. Lists

Reverse A List

Introduction

Python is a flexible language, and there's typically several ways to perform the same, menial task. Choosing an approach can depend on the time or space complexity, or simply on your personal preference.

Python's data structures are quite handy and intuitive, and their built-in functionalities are easy to work with. In this article, we'll be looking at how to reverse a list in Python. A Python List is a heterogenous (can contain differing types) array-like structure that stores references to objects in memory.

When manipulating a list, we can either create a new, changed list, or change the original list in-place. We'll see the differences in these as we proceed through the article.

Reverse a List Using the reverse() Method

Python has a powerful built-in library of methods when it comes to manipulating data in data structures. For the purposes of reversing a list, we can utilize the built-in reverse() method.

Note: The reverse() method reverses the list in-place. Reversing a list in-place means that the original list is changed, instead of creating a new, reversed list.

Due to this, we can't assign the resulting object to a new variable, and if you want to keep the original list in memory, you'll have to copy it before reversing:

my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]

new_list = my_list.reverse()
print(new_list) # Output: None

There's no return value - the list is reversed in-place. However, we can copy() it before reversing:

list_1 = [1, 2, 3, 4]
list_2 = list_1.copy()

list_1.reverse()

print('Reversed list: ', list_1)
print('Saved original list: ', list_2)

This results in

Reversed list:  [4, 3, 2, 1]
Saved original list:  [1, 2, 3, 4]

Reverse a List Using Slice Notation

When you slice a list, a portion is returned from that list, and every stepth element is included:

my_list = [1, 2, 3, 4, 5, 6]

# list[start:end:step]
segment_1 = my_list[1:5:1]
segment_2 = my_list[1:5:2]

print(segment_1)
print(segment_2)

This results in:

[2, 3, 4, 5]
[2, 4]

By omitting the start and end arguments, you can include the entire collection. And by setting the step to a negative number, you iterate through the collection in reverse. Naturally, if you pair these together:

original_list = [1, 2, 3, 4, 5, 6]

reversed_list = original_list[::-1]
print('Original list: ', original_list)
print('Reversed list: ', reversed_list)

This results in:

Original list:  [1, 2, 3, 4, 5, 6]
Reversed list:  [6, 5, 4, 3, 2, 1]

The Slice Notation doesn't affect the original list at all, so the original_list stays the same even after the operation.

Reverse a List Using slice() Method

The slice() method accepts the very same parameters - start, end and step, and performs much the same operation as the Slice Notation. Though, instead of omitting the start and end arguments, you can pass in None.

Its return type is a Slice object, which can be then be used to slice a collection according to its contents. It's not called on the collection you're slicing - you're passing in the Slice object after creation, allowing you to create a single reusable and callable object for many different collections.

It's internally transpiled into Slice Notation, so the end result is the same:

original_list = [1, 2, 3, 4, 5, 6]

slice_obj = slice(None, None, -1)

print('slice_obj type:', type(slice_obj))
print('Reversed list:', original_list[slice_obj])

This results in:

slice_obj type: <class 'slice'>
Reversed list: [6, 5, 4, 3, 2, 1]

Reverse a List Using a For Loop

Depending on whether we want to keep the original list intact or not, we can pop() elements from the original list and add them to a new one, or we can just append them in reverse order.

pop() removes the last element from a collection and returns it. We can combine the append() method with this to directly append the removed element to a new list, effectively resulting in a reversed list:

original_list = [1, 2, 3, 4] 
reversed_list = []

for i in range(len(original_list)):
    reversed_list.append(original_list.pop())

print(reversed_list) # Output: [4, 3, 2, 1]

Alternatively, we can iterate through the list backwards, until the -1th index (non-inclusive) and add each element we see along that list. The range() method accepts 3 arguments - start, end and step, which can again be used in much the same way as before:

original_list = [1, 2, 3, 4]
reversed_list = []

for i in range(len(original_list)-1, -1, -1):
    reversed_list.append(original_list[i])

print(reversed_list) # Output: [4, 3, 2, 1]

Reversing a List Using the reversed() Method

Since iterating with a negative step and then accessing each element in the original list is a bit verbose, the reversed() method was added, which makes it much easier to manually implement the reversal logic, in case you want to add your own twist on it.

The reversed() method returns an iterator, iterating over the collection in a reversed order - and we can easily add these elements into a new list:

original_list = [1, 2, 3, 4]
new_list = []

for i in reversed(original_list):
	new_list.append(i)
    
print(new_list) # Output: [4, 3, 2, 1]
print(original_list) # Output: [1, 2, 3, 4] --> Original hasn't changed

Conclusion

Depending on whether you need a new reversed list, an in-place reversed list, as well as whether you want the logic to be taken care of for you, or if you'd like to have the flexibility of adding additional operations or twists during the reversal - there are several ways to reverse a list in Python.

In this tutorial, we've gone over these scenarios, highlighting the difference between each.

PreviousListsNextPython Data Structures

Last updated 3 years ago

Was this helpful?

The slice notation allows us to slice and reproduce parts of various collections or collection-based objects in Python, such as , , and .

Lists
Strings
Tuples
NumPy Arrays