How to reverse array python

Reverse an Array in Python – 10 Examples

Reversing Arrays In Python

In this tutorial, we’ll go over the different methods to reverse an array in Python. The Python language does not come with array data structure support. Instead, it has in-built list structures that are easy to use as well as provide some methods to perform operations.

We can continue to use the typical Arrays in Python by import a module like Array or NumPy. Our tutorial is going to be divided into three parts, each dealing with reversing individual Array types in Python. They are,

  • Reversing an Array List in Python,
  • Reversing an Array of Array Module in Python,
  • Reversing a NumPy Array in Python.

Upskill 2x faster with Educative

Supercharge your skillset with Educative Python courses → use code: ASK15 to save 15%

Читайте также:  Python rename file in folder

Now let us get right into the topic.

Reverse a List Array in Python

As we already discussed Lists and Arrays are similar in Python. Where the major difference among the two is that arrays only allow items of the same data type whereas lists allow them to be different.

Since Python doesn’t support conventional Arrays, we can use lists to depict the same and try to reverse them. Let us take a look at the different methods following which we can accomplish this task.

1. Using List Slicing to Reverse an Array in Python

We can reverse a list array using slicing methods. In this way, we actually create a new list in the reverse order as that of the original one. Let us see how:

#The original array arr = [11, 22, 33, 44, 55] print("Array is :",arr) res = arr[::-1] #reversing using list slicing print("Resultant new reversed array:",res)
Array is : [1, 2, 3, 4, 5] Resultant new reversed array: [5, 4, 3, 2, 1]

2. Using reverse() Method

Python also provides a built-in method reverse() that directly reverses the order of list items right at the original place.

Note: In this way, we change the order of the actual list. Hence, the original order is lost.

#The original array arr = [11, 22, 33, 44, 55] print("Before reversal Array is :",arr) arr.reverse() #reversing using reverse() print("After reversing Array:",arr)
Before reversal Array is : [11, 22, 33, 44, 55] After reversing Array: [55, 44, 33, 22, 11]

3. Using reversed() Method

We have yet another method, reversed() which when passed with a list returns an iterable having just items of the list in reverse order. If we use the list() method on this iterable object, we get a new list which contains our reversed array.

#The original array arr = [12, 34, 56, 78] print("Original Array is :",arr) #reversing using reversed() result=list(reversed(arr)) print("Resultant new reversed Array:",result)
Original Array is : [12, 34, 56, 78] Resultant new reversed Array: [78, 56, 34, 12]

Reversing an Array of Array Module in Python

Even though Python doesn’t support arrays, we can use the Array module to create array-like objects of different data types. Though this module enforces a lot of restrictions when it comes to the array’s data type, it is widely used to work with array data structures in Python.

Now, let us see how we can reverse an array in Python created with the Array module.

1. Using reverse() Method

Similar to lists, the reverse() method can also be used to directly reverse an array in Python of the Array module. It reverses an array at its original location, hence doesn’t require extra space for storing the results.

import array #The original array new_arr=array.array('i',[2,4,6,8,10,12]) print("Original Array is :",new_arr) #reversing using reverse() new_arr.reverse() print("Reversed Array:",new_arr)
Original Array is : array('i', [2, 4, 6, 8, 10, 12]) Resultant new reversed Array: array('i', [12, 10, 8, 6, 4, 2])

2. Using reversed() Method

Again, the reversed() method when passed with an array, returns an iterable with elements in reverse order. Look at the example below, it shows how we can reverse an array using this method.

import array #The original array new_arr=array.array('i',[10,20,30,40]) print("Original Array is :",new_arr) #reversing using reversed() res_arr=array.array('i',reversed(new_arr)) print("Resultant Reversed Array:",res_arr)
Original Array is : array('i', [10, 20, 30, 40]) Resultant Reversed Array: array('i', [40, 30, 20, 10])

Reversing a NumPy Array in Python

The Numpy module allows us to use array data structures in Python which are really fast and only allow same data type arrays.

Here, we are going to reverse an array in Python built with the NumPy module.

1. Using flip() Method

The flip() method in the NumPy module reverses the order of a NumPy array and returns the NumPy array object.

import numpy as np #The original NumPy array new_arr=np.array(['A','s','k','P','y','t','h','o','n']) print("Original Array is :",new_arr) #reversing using flip() Method res_arr=np.flip(new_arr) print("Resultant Reversed Array:",res_arr)
Original Array is : ['A' 's' 'k' 'P' 'y' 't' 'h' 'o' 'n'] Resultant Reversed Array: ['n' 'o' 'h' 't' 'y' 'P' 'k' 's' 'A']

2. Using flipud() Method

The flipud() method is yet another method in the NumPy module which flips an array up/down. It can also be used to reverse a NumPy array in Python. Let us see how we can use it in a small example.

import numpy as np #The original NumPy array new_arr=np.array(['A','s','k','P','y','t','h','o','n']) print("Original Array is :",new_arr) #reversing using flipud() Method res_arr=np.flipud(new_arr) print("Resultant Reversed Array:",res_arr)
Original Array is : ['A' 's' 'k' 'P' 'y' 't' 'h' 'o' 'n'] Resultant Reversed Array: ['n' 'o' 'h' 't' 'y' 'P' 'k' 's' 'A']

3. Using Simple Slicing

As we did earlier with lists, we can reverse an array in Python built with Numpy using slicing. We create a new NumPy array object which holds items in a reversed order.

import numpy as np #The original NumPy array new_arr=np.array([1,3,5,7,9]) print("Original Array is :",new_arr) #reversing using array slicing res_arr=new_arr[::-1] print("Resultant Reversed Array:",res_arr)
Original Array is : [1 3 5 7 9] Resultant Reversed Array: [9 7 5 3 1]

Conclusion

So, in this tutorial, we learned how we can reverse an array in Python using various methods or techniques. Hope it gives a clear understanding.

References

Источник

Python Reverse List – How to Reverse a Range or Array

Dionysia Lemonaki

Dionysia Lemonaki

Python Reverse List – How to Reverse a Range or Array

In this tutorial, you’ll learn some of the different ways you can reverse lists and list ranges in Python. And we’ll look at some coding examples along the way.

How to create a range in Python

An efficient way to create a list of a range of numbers in Python is to use the built-in range() function.

To create a list with a range of numbers, you use the list() constructor and inside that, the range() function.

The range function takes up to three paramaters – the start, stop, and step parameters, with the basic syntax looking something like this:

The start parameter is the number from which the counting will start.

The stop parameter is the number up to – but not including – the one where the counting will stop.

The step parameter is the number that determines how numbers will be incremented.

Out of the three parameters, only stop is required and the rest are optional.

If you only include the stop parameter, keep in mind that by default the counting starts at 0 and then the counting ends one number before the one you specified.

#creates a list of numbers that #start at 0 and end at 3, not 4. my_range = list(range(4)) print(my_range) #output #[0, 1, 2, 3] 

So, here is how you would put all these together in order to create a list of a range of numbers:

#creates a list of range of numbers: #starting from 0 #up to, but not including, 10 # and the counting is incremented by 1 my_range = list(range(0, 10, 1)) #print to the console print(my_range) #output #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #check type using the built-in type() method print(type(my_range)) #output #

How to reverse a range in Python

To reverse a range of numbers in Python with the range() function, you use a negative step, like -1 .

The example below creates a list of a range of numbers starting from 9 up to, but not including, -1 (so the counting stops at 0) and the counting of the sequence is decremented by 1 each time:

my_range = list(range(9, -1, -1)) print(my_range) #output #[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] print(type(my_range)) #

When reversing a list, you need to include the start and step parameters.

How to reverse an array in Python

An array in programming is an ordered collection of items, all of which are of the same data type.

Each item in the collection has an its own index number.

However, unlike other programming languages, arrays aren’t a built-in data structure in Python.

Instead, you use lists, and Python offers a few ways to reverse them.

How to reverse a list in Python using the .reverse() method

Using this built-in Python method, the list changes in place. This means that the original order of the list is affected.

The initial order of the items gets updated and altered.

For example, say you have the following list:

#initial list my_list = [10,20,30,40,50] print("My initial list is: ",my_list) #output #My initial list is: [10, 20, 30, 40, 50] 

To change my_list ‘s items to have an order of 50, 40, 30, 20,10 , you’d do:

#initial list my_list = [10,20,30,40,50] #reverse order of items my_list.reverse() print("This is what the list looks like now: ", my_list) #output #This is what the list looks like now: [50, 40, 30, 20, 10] 

You see that the initial order of the list has now changed and the elements inside it have been reversed.

How to reverse a list in Python using the slicing operator

The slicing operator works similarly to the range() function you saw earlier on.

It also accepts the start , stop , step arguments.

The syntax looks like this: start:end:step .

my_list = [10,20,30,40,50] my_list2 = my_list[1:3:1] print(my_list2) #output #[20, 30] 

In the example above, we wanted to fetch the items starting from index 1 up to, but not including, the item with index 3, incrementing one number at a time.

Indexing in Python starts from 0, so the first element has an index of 0, the second element has an index of 1, and so on.

When you want to print all items, you use one of the two following ways:

my_list = [10,20,30,40,50] my_list2 = my_list[:] #or.. my_list2 = my_list[::] #print to the console print(my_list2) #output #10, 20, 30, 40, 50] 

So, you either use one or two colons to output all items contained in the list.

Now, to reverse all the items inside the list using the slicing operator, you have to include the step.

In this case you use two colons to represent the start and end arguments, and a negative step for decrementing:

my_list = [10,20,30,40,50] my_list2 = my_list[::-1] print(my_list2) #output #[50, 40, 30, 20, 10] 

In this case a new list is created, with the original order of the list not being affected.

How to reverse a list in Python using the reversed() function

Don’t confuse this with the .reverse() method! The built-in reversed() function reverses the order of a list and lets you access each individual item one at a time.

my_list = [10,20,30,40,50] for num in reversed(my_list): print(num) #output #50 #40 #30 #20 #10 

The reversed() function accepts a list as an argument and returns an iterable, reversed version of the items contained in the list.

If you wanted to store the return value from the reversed() function for later use, you’d instead have to enclose it inside the list() constructor and assign the new list to a variable, like so:

#initial list my_list = [10,20,30,40,50] #use reversed() function to reverse order of my_list #store new list that gets created to the variable my_new_list my_new_list = list(reversed(my_list)) print(my_new_list) #output #[50, 40, 30, 20, 10] 

Conclusion

And there you have it — you now know the basics of how reversing lists in Python works!

If you want to learn more about Python, freeCodeCamp offers a Python certification

In this project-based curriculum, you’ll start from the ground up. You’ll learn programming fundamentals and advance to more complex topics. In the end you’ll build 5 projects to put your new skills to practice.

Thanks for reading and happy coding!

Источник

Оцените статью