Reverse a list Python without slicing

Example reverse a list in Python without reverse function

Simple example code.

Swap method

list1 = [1, 2, 3, 4, 5] L = len[list1] for i in range[int[L / 2]]: n = list1[i] list1[i] = list1[L - i - 1] list1[L - i - 1] = n print[list1]

Output:

Recursion Function

list1 = [1, 2, 3, 4, 5] def reverse_fun[numbers]: if len[numbers] == 1: return numbers # Otherwise return reverse_fun[numbers[1:]] + numbers[0:1] print[reverse_fun[list1]]

Sice notation

list1 = ['A', 'B', 'C', 'D'] def reverse[data_list]: return data_list[::-1] print[reverse[list1]]

Output: [‘D’, ‘C’, ‘B’, ‘A’]

Create a reverse method for a python list from scratch

def reverse_fun[data_list]: length = len[data_list] s = length new_list = [None] * length for item in data_list: s = s - 1 new_list[s] = item return new_list list1 = [1, 2, 3, 4, 5] print[reverse_fun[list1]]

Output: [5, 4, 3, 2, 1]

Do comment if you have questions and suggestions on this Python list tutorial.

Note: IDE:PyCharm2021.3 [Community Edition]

Windows 10

Python 3.10.1

AllPython Examplesare inPython3, so Maybe its different from python 2 or upgraded versions.

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

Share this:

  • Facebook
  • WhatsApp
  • LinkedIn
  • More
  • Twitter
  • Print
  • Reddit
  • Tumblr
  • Pinterest
  • Pocket
  • Telegram
  • Skype
  • Email

Related

Reverse Python Lists: Beyond .reverse[] and reversed[]

by Leodanis Pozo Ramos Jun 28, 2021 basics python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Are you diving deeper into Python lists and wanting to learn about different ways to reverse them? If so, then this tutorial is for you. Here, you’ll learn about a few Python tools and techniques that are handy when it comes to reversing lists or manipulating them in reverse order. This knowledge will complement and improve your list-related skills and make you more proficient with them.

In this tutorial, you’ll learn how to:

  • Reverse existing lists in place using .reverse[] and other techniques
  • Create reversed copies of existing lists using reversed[] and slicing
  • Use iteration, comprehensions, and recursion to create reversed lists
  • Iterate over your lists in reverse order
  • Sort your lists in reverse order using .sort[] and sorted[]

To get the most out of this tutorial, it would be helpful to know the basics of iterables, for loops, lists, list comprehensions, generator expressions, and recursion.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

How to Reverse a List in Python

By Dan Bader — Get free updates of new posts here.

A step-by-step tutorial on the three main ways to reverse a Python list or array: in-place reversal, list slicing, and reverse iteration.

Reversing a list is a common operation in Python programming.

For example, imagine you had a sorted list of customer names that your program displays in alphabetical [A-Z] order. Some of your users would like to view the customer list so that the names are in reverse alphabetical order. How are you going to flip the order of this existing list on its head? Or in other words:

What’s the best way to reverse the order of a list in Python?

In this article you’ll see three different ways to achieve this result in “plain vanilla” Python, meaning without the use of any third-party libraries:

  1. Reversing a list in-place with the list.reverse[] method
  2. Using the “[::-1]” list slicing trick to create a reversed copy
  3. Creating a reverse iterator with the reversed[] built-in function

All examples I’m using here will be based on the following list object containing the numbers 1 through 5:

# You have this: [1, 2, 3, 4, 5] # And you want that: [5, 4, 3, 2, 1]

Ready? Let’s reverse some lists together!

Python Lists and List Slicing: A Refresher

In Python, lists are arrays of items. Your list could include strings, booleans, numbers, objects, or any other data type in Python, and can hold as many as you want. When working with a lot of data, it can be useful to declare a list instead of declaring multiple variables.

List Slicing

While you don’t need to know about list slicing to perform a reverse list operation, it can be helpful.

This is how you would declare a list in Python:

studentNames = ["Hannah", "Imogen", "Lewis", "Peter"]

We have just declared a variable, studentNames, and assigned a list of values—in this case, the names of students—to the variable.

If we want to get a particular value from our list, we can use its index numbers and slice the list. That’s a lot to take in, so let’s break it down. Each item in our list has an index value, starting from 0. We can use them to get a certain value from our list. Here are the index values for our array:

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today
» MORE: Python Find: A Guide
HannahImogenLewisPeter
123

If we want to get Imogen from our list, we would do so using the following code:

studentNames = ["Hannah", "Imogen", "Lewis", "Peter"] print[studentNames[1]]

We have declared our variable with student names. Next, we said we want to get the list item with the index value of 1. In this case, the value was Imogen.

We can also change the index number to get a range by adding another one. Here’s an example:

studentNames = ["Hannah", "Imogen", "Lewis", "Peter"] print[studentNames[1:3]]

The output for our code would be as follows:

["Imogen", "Lewis", "Peter"]

Now we know the basics of list slicing, we can start to discuss reversing lists in Python.

How to reverse a list in python without using reverse function

ByMohammed Abualrob Articles and Tutorials, Code Snippets 3 Comments

Introduction

In this Python code snippet post, we are going to implement a list reverse function from the scratch without using any builtin functions.

Let us see how…

Iterative solution

We can use a for loop to swap the first and last items, the second and the one before the last item and so on until the list is reversed in place. The number of iterations needed is half the list size. If the list has an odd number of items then the middle item will stay in its place.

Here is an example Python code to do that

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Example input list of numbers
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get list length
L = len[numbers]
# i goes from 0 to the middle
for i in range[int[L/2]]:
# Swap each number with the number in
# the mirror position for example first
# and last
n = numbers[i]
numbers[i] = numbers[L-i-1]
numbers[L-i-1] = n
# At this point the list should be reversed
print[numbers]

Recursion solution

We can write a recursive reverse function to reverse a list. The stopping condition occurs when the list is one item in length in such case we just return that list otherwise we return list concatenation constructed from the first item and the recursive reverse of the rest of the items. For example Reverse[[1, 2, 3, 4]] = Reverse[[2, 3, 4]] + [1].

Here is an example implementation…

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
# Example input list of numbers
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Function takes a list as input
def Reverse[numbers]:
# Base case when the list is only one item
if [len[numbers]==1]:
return numbers
# Otherwise
return Reverse[numbers[1:]] + numbers[0:1]
# Test function
print[Reverse[numbers]]

I hope this post was useful. Thanks for visiting

More from my site

  • Wikipedia Summary Python API
  • Connect to MS SQL Server using Python on Mac
  • How to beautify and pretty print formatted JSON in Python
  • Python recursive function examples
  • Yelp Fusion API Python example
  • Godaddy domain name API in Python
Tags:Python

About Author

Mohammed Abualrob

Software Engineer @ Cisco

3 Comments
  1. Anirudh

    this method will only work for list that has even number of elements

    June 17, 2020 Reply
    • Sky

      NO it works for both odd and even.

      August 29, 2020 Reply
  2. Anonymous

    it works for both the recursive method has nothing to do with even

    August 2, 2021 Reply

Add a Comment

Cancel reply

Your email address will not be published. Required fields are marked *

Comment:*

Name:*

Email Address:*

Website:

Save my name, email, and website in this browser for the next time I comment.

Δ

Reverse a list in python with reverse function

Python has an in-built function called reverse[] that we can use to reverse a Python list. Let us see an example. We will create a list and reverse it using the reverse[] function. have a look at the code below.

list1=[12,14,56,24,25,52,54] list1.reverse[] print[list1]
  • We have created a list with the name list1 and used the reverse[] fucntion to reverse the list. Look at the output below:
Reversed list

In this way, you can use the in-built reverse[] function to reverse a list.

Read: Python program to reverse a string

Reversing a List in Python

Python provides us with various ways of reversing a list. We will go through few of the many techniques on how a list in python can be reversed.
Examples:

Input : list = [10, 11, 12, 13, 14, 15] Output : [15, 14, 13, 12, 11, 10] Input : list = [4, 5, 6, 7, 8, 9] Output : [9, 8, 7, 6, 5, 4]

Get a reversed list using reversed[] function

Python provides a builtin function reversed[] i.e.

reversed[seq]
It accepts a sequence and returns a reversed Iterator of the given sequence. We can use this reverse iterator to iterate over the contents of the sequence, or we can pass this iterator to list[] function, to create a new list of reversed contents of the sequence. Let’s use this reversed[] function to get a copy of list with reversed contents,
list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59] # Get a list with reversed contents reversed_list = list[reversed[list_of_num]] print[reversed_list]
Output:
[59, 58, 57, 56, 55, 54, 53, 52, 51]
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. In the end it returned that reversed list as a copy of the original list.

Video liên quan

Bài mới nhất

Chủ Đề