How to Reverse Python Lists | In-place, slicing & reversed()
Python lists can be reversed using built-in methods reverse(), reversed() or by [::-1] list slicing technique. The reverse() built-in method reverses the list in place while the slicing technique creates a copy of the original list. The reversed() method simply returns a list iterator that returns elements in reverse order.
Below are the three built-in, common method used for reversing Python lists.
1. Reversing lists in-place using reverse()
2. Reversing lists using slicing (creates a new copy)
3. Reversing lists using reversed
Let us look at each in detail to understand pros, cons and when to use a particular method.
Using reverse() for In-Place List Reversal
Time and Space Complexity of Python List reverse()
The reverse() method works in O(n) time complexity and with O(1) space. Internally, when reverse() is called it operates by swapping i-th element with (n-i)th element. Therefore, the first element is replaced with the last element, the second element is replaced with the second last element and so on. Thus, a total of N/2 swap operations are required for list reversal. That makes the overall time complexity as O(N/2) which is same as O(N)
Pros of reverse methods:
- In-Place
- Intuitive and easy to understand, it upholds code readability.
Cons of reverse() method:
- The order of elements in the original list is changed.
When to use reverse() methods ?
Scenarios where order of elements in the original list can be altered and keeping a low memory footprint is desired .
Using Slicing For Python List Reversal
Python lists can be reversed using the [::-1] slicing suffix. It creates and returns a new copy of the list without altering the actual list.
What does [::-1] notation mean? It means to select elements starting from the first element till the last element with a stride of negative one, i.e, in reverse order. The list slicing notation is [start:end:step], so here start=end=None means the defaults (0 and n-1) and step=-1 implies reverse order.
What are the pros, cons of using slicing for list reversal, and when should we prefer slicing over reverse() or reversed() ?
Pros of list slicing for list reversal:
- The original list is not altered. The order of elements in the original arrays is maintained before and after the slicing operation.
Cons:
- Takes extra space by creating a list of the same size.
- While [::-1] notation is shorter, it is cryptic and requires more attention to understand as compared to english words syntax reverse() or reversed(). In short not the best for code readability.
When to use slicing or Python List Reversal:
- If it is a requirement to preserve the order of elements in the original list.
- It is fine to allocate extra memory for the copy of the list.
Using reversed() for Python list reversal
Python lists can also be reversed using the built-in reversed() method. The reversed() method neither reverses the list in-place nor it creates a copy of the full list. It instead returns a list iterator(listreverseiterator) that generates elements of the list in reverse order.
Note that calling reversed(nums) simply returns an iterator object. We can see in the following example that the reverse_python_list method, which simply wraps the reversed() method, does not modify the original list or create a copy of the list.
Pros of reversed() for list reversal:
- No extra space is required
- The original list remains unchanged
- The syntax aids to code readability
Cons:
- None really. Just that extra caution needs to be exercised with iterators.The returned iterator can be used only once(it gets exhausted on looping over once). So, if it is required to access the reversed list multiple times, we need to create a copy of the list or call the reversed() function multiple times.
Common List Reversal Problems
Let us take a look at a few other common Python Lists reversal related problems.
How to reverse a list in python using for loop ?
To reverse a list of size n using for loop, iterate on the list from (n-1)th element to the first element and yield each element.
How to reverse python list using recursion ?
To reverse a list of using recursion, we define a method that returns sum of two lists, the first being the last element (selected by -1 index) and the second one being reverse of the entire list upto the last element (selected by :-1). The base condition is met when all the elements are exhausted and the array is empty, upon which we return an empty array. Below is the functional code.
How to reverse part(subset or slice) of Python list?
To reverse a part of a list, the built-in reverse, reversed or slicing methods can be used on the subset identified by slicing. The following code shows all the three approaches:
How to reverse Python Numpy Array?
The numpy arrays can be reversed using the slicing technique (using [::-1] slice descriptor) or by using numpy’s flipud method. The following code shows the usage of both:
Summary
In this tutorial we learnt the three techniques for Python list reversal, viz reverse(), reversed() and slicing. We also looked at the pros and cons of each method.
So, which is the best way to reverse list in python?
The answer depends on the requirements. If the requirement is to maintain the order of original elements then reversed() or slicing technique should be used. If the requirement is to have minimal memory footprint, reverse() or reversed() are more suited. If it is required to have a minimal memory footprint along with maintaining order of elements in the original list, reversed() should be used. In general, if there is no such preference, reverse() or reversed() can be preferred over slicing technique as it aids to code readability.
8 Ways To Reverse The Elements In A Python List
![]()
Lists are one of the in-built data types in Python and fall into the sequence category. That means lists are used for working with the sequence of objects and we can say a sequence is a Python list when they are wrapped within ( [ ] ) square brackets.
Just like other data types, lists have numerous methods and function which helps us in modifying and manipulating the elements inside the list.
Python list has a function named reverse() which is used to reverse the elements of the list.
But in this article, you’ll see the various ways to reverse the elements specified inside the list. The list.reverse() function is one you might know but you’ll also see other ways to perform the same operation.
Using list.reverse()
Python list.reverse() used to reverse the elements specified inside the list. If you notice that it is list.reverse , this function is specific to Python lists and cannot be used for other data types.
In the following example, a list is defined and stored in the my_lst variable and then performed the reverse operation. This will reverse the order of the elements.
Output
Note: If you try to reverse any data type other than lists, an AttributeError will be raised stating that ‘x’ has no attribute ‘reverse’.
Using reversed()
Python reversed() function is also used to reverse the elements inside the list. Still, instead of returning the reversed object, it returns the reversed iterator object that accesses the values of a given sequence. To access the values, you have to iterate them either by using the for loop or the next() function.
Consider the following example, the list object my_lst is reversed and then accessed the values using the next() function from the reversed iterator object new_lst .
Output
One main thing is Python reversed() isn’t like the list.reverse() function because it can be used for any iterable sequence.
Using list comprehension
Using list comprehension for reversing the list is different from the approach you’ve seen in the above two ways.
In the above Python program, a list is defined and then the variable index is defined that stores the list’s index value by taking the list’s length minus 1. Then created a list comprehension that accesses each index item of the list using the range function from the index to the end of the list in reverse order.
Output
Using for loops
Python for loop is a great way to iterate over a sequence. Let’s see how to reverse a list using the for loop.
First, we defined two lists, one is our original list( my_lst ) and the other is the empty list( rev_list ) to store the reversed elements.
Then we iterated over each element from the original list and added them to our empty list named rev_list . The output will be a reversed version of the original list.
Output
If you are wondering how it happened, then look at the example below
If we print rev_list each time the elements from the original list are added then at the end we’ll get the reversed list.
Using reverse list indexing
The elements in Python lists have an index value which helps in accessing the specific element. The index value starts from 0 to n-1 . List indexing can be done using the format [start : stop: step] .
For example, [: : 1] will return the whole list from start to end. Similarly, [: : -1] will return the list but in reversed order. Let’s see an example.
The above code will step over the elements from the original list in reverse order.
Using slice method
Python has a function called slice() that returns a slice object which is used to specify how to slice a sequence. It takes 3 arguments ( start, stop, step ). start that specifies from where to start slicing, stop that specifies where to end and step that specifies the step of the slicing.
In the above program, created a slice object that reverses the order of the original list and is then used to reverse the original list.
Using range function
In the above Python program, we are using a range() function that is grabbing the last index value of the item and going all the way to the end in the reverse order. It is just like what we’ve done using list comprehension.
Using __reversed__()
Python list has a special method called __reversed__() that helps in reverse iteration. If you remember we saw the reversed() function, basically it runs the __reversed__() method in the backend to reverse the input list.
Output
Conclusion
You’ve learned the various ways that you can use to reverse the Python lists. Some of the ways you might already know and some don’t.
Let’s recall the methods you’ve learned in this article to reverse the list:
Python Reverse List – Reversing an Array in Python

Dionysia Lemonaki

In this article, you will learn how to reverse a list in Python.
Firstly, I’ll introduce you to lists in Python and you’ll learn how to write them. After that, you will see three different ways you can reverse the list items inside any list you create.
Here is what we will cover:
What Is a List in Python? How to Write a List in Python Example
Lists are a built-in data type in Python and one of the most powerful data structures.
You can think of them as containers for storing multiple (typically related) collections of items under the same variable name.
To create a list in Python, you need to:
- Give the list a name.
- Use the assignment operator, = .
- Include 0 or more list items inside square brackets, [] – and make sure to separate each list item with a comma.
List items can be homogeneous, meaning they are of the same type.
For example, you can create a list of only numbers or a list of only strings (or text).
Here is how you would create a list of names:
The example above created a list of names with four values: Johny , Lenny , Jimmy , and Timmy .
You can also create only a list of integers (or whole numbers):
List items can also be heterogeneous, meaning they can all be of different data types.
This is what sets lists apart from arrays.
Unlike arrays, that only store items of the same type, lists allow for more flexibility.
Arrays require that items are only of the same data type, whereas lists do not.
Lists are mutable, meaning they are changeable and dynamic – you can update, delete, and add new list items to the list at any time throughout the life of the program.
How to Reverse Items in a List Using the .reverse() Method
The .reverse() method in Python is a built-in method that reverses the list in place.
Reversing the list in place means that the method modifies and changes the original list. It doesn’t create a new list which is a copy of the original but with the list items in reverse order.
This method is helpful when you are not concerned about preserving the order of the original list.
The general syntax of the .reverse() method looks something like the following:
The .reverse() method doesn’t accept any arguments and doesn’t have a return value – it only updates the existing list.
Here is how you would use the .reverse() method to reverse a list of integers:
In the example above, the order of the list items in the original list is reversed, and the original list is modified and updated.
And here is how you would use the method on a list of names:
How to Reverse Items in a List Using the reversed() Function
This function is helpful when you want to access the individual list elements in reverse order.
The general syntax for the reversed() function looks something similar to this:
The reversed() built-in function in Python returns a reversed iterator – an iterable object which is then used to retrieve and go through all the list elements in reverse order.
Returning an iterable object means that the function returns the list items in reverse order. It doesn’t reverse the list in place. This means that it doesn’t modify the original list, nor does it create a new list which is a copy of the original one but with the list items in reverse order.
You use the reversed() function with a for loop to iterate through the list items in reversed order. (If you need a refresher on for loops in Python, have a read through this article)
If you then print the contents of the original list to the console, you will see that the order of the items is preserved, and the original list is not modified:
This is because the reversed() function takes a list as an argument and returns an iterator in reverse order.
It will not make any changes to the existing list, and it will not create a new one.
This function doesn’t reverse the list permanently, only temporarily during the execution of the for loop on the original list.
But what if you want to create a new list that will be a copy of the original one but with the items in reversed order using the reversed() function?
You can pass the result of the reversed() operation as an argument to the list() function, which will convert the iterator to a list, and store the final result in a variable:
How to Reverse Items in a List Using Slicing
Another way of reversing lists in Python is by using slicing.
Slicing is one of the fastest ways to reverse a list in Python and offers a concise syntax. That said, it is more of an intermediate to advanced feature and not that beginner friendly compared to the .reverse() method, which is more intuitive and self-descriptive.
Let’s go over a quick overview of how slicing works.
The general syntax looks something like the following:
Let’s break it down:
start is the beginning index of the slice, inclusive.
Indexing in Python and Computer Science starts at 0 .
The default value of start is 0 , and it grabs the first item from the beginning of the list.
If you want to get the first item from the end of the list, the value would be -1 .
stop is the ending index position and where you want the slicing to stop, not inclusive – it does not include the element located at the index you specify.
For example, if you want to slice the list from the beginning up until the item with the index 3 , here is what you would do:
step is the increment value, with the default value being 1 .
Now, when it comes to using slicing for reversing a list, you would need to use the reverse slicing operator [::-1] syntax. This sets the step to -1 and gets all items in the list in reverse order.
The slicing operator does not modify the original list. Rather it returns a new list, which is a copy of the items from the original list in reverse order.
Conclusion
And there you have it! You now know how to reverse any list in Python.
I hope you found this tutorial helpful.
To learn more about the Python programming language, check out freeCodeCamp’s Python certification.
You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
Как перевернуть список в Python
В этом руководстве мы расскажем, как перевернуть список в Python. Мы разберем несколько разных способов реверсирования списков и диапазонов списков на примерах.
Итак, давайте начнем!
От редакции Pythonist. Также рекомендуем статью «Как перевернуть строку в Python».
Как создать диапазон элементов в Python
Наиболее простой и эффективный способ создать диапазон чисел в Python – использовать встроенную функцию range() .
Чтобы создать список с диапазоном чисел, мы воспользуемся функцией list() и внутри нее укажем функцию range() .
Функция range() принимает до трех параметров – это параметры start , stop и step , при этом общий синтаксис выглядит так:
range(start, stop, step)
Параметр start – это число, с которого начнется отсчет. По умолчанию данный параметр равен 0. Таким образом, мы формируем наш диапазон, начиная с нулевого элемента.
Параметр stop – это число, на котором счет будет остановлен. Важно отметить, что последнее число, которое войдет в диапазон – stop-1 .
И последний параметр — step . Это число, которое определяет, как числа будут увеличиваться. То есть с каким шагом мы будем идти. По умолчанию, step=1 , то есть мы перебираем числа одно за другим.
Из этих трех параметров обязательным является только stop , остальные указываются опционально.
Если вы передаете функции range() только параметр stop , по умолчанию отсчет начнется с 0, а закончится на одно число перед указанным вами.
Рассмотрим пример, чтобы лучше понять, как это работает:
А вот так будет выглядеть пример, если передать сразу все 3 аргумента:
Ещё раз заметим, что в данном случае параметры start и step можно было не передавать, так как они по умолчанию и так равны 0 и 1 соответственно.
Как перевернуть диапазон в Python
Чтобы перевернуть диапазон чисел в Python с помощью функции range() , можно использовать отрицательный шаг, например -1. То есть в качестве третьего параметра step вы передаете отрицательное число. Тогда в результате мы получим исходный диапазон в обратном порядке.
В приведенном ниже примере создается список из диапазона чисел от 9 до -1. Однако последнее число мы не включаем, поэтому последним элементом диапазона будет ноль. А шаг равен -1, то есть мы пойдем в обратную сторону, перебирая все числа одно за другим.
Для того, чтобы переворачивать диапазоны в рамках функции range() , нужно передавать все три аргумента: start , stop и step . При этом step обязательно должен быть отрицательным.
Как перевернуть массив в Python
В программировании массив – это упорядоченный набор элементов, каждый из которых имеет один и тот же тип данных.
Каждый элемент в массиве имеет собственный порядковый номер (индекс).
Однако, в отличие от других языков программирования, в Python массивы не являются встроенной структурой данных. Для работы с массивами их нужно импортировать из сторонних библиотек (Numpy).
Вместо этого мы используем списки. А для поворота списков Python предлагает несколько способов. Давайте их рассмотрим!
Как перевернуть список в Python с помощью метода .reverse()
При использовании данного встроенного метода в Python список изменяется сразу же. Это означает, что изменяется исходный порядок данного списка.
Первоначальный порядок элементов исходного списка изменяется и тут же обновляется.
Например, предположим, что у нас есть следующий список:
Чтобы изменить порядок элементов списка my_list на 50, 40, 30, 20, 10, выполним следующее:
Как видно из результата, начальный порядок списка теперь изменился, а элементы внутри него теперь стоят в обратном порядке.
Как перевернуть список в Python с помощью срезов
Срезы работают аналогично функции range() , которую мы разобрали ранее.
Срез также включает в себе три параметра: start , stop и step .
Синтаксис выглядит следующим образом: [start:end:step] .
К примеру, давайте рассмотрим такой случай:
В приведенном выше примере мы хотели получить каждый элемент из исходного списка, начиная с индекса 1 до индекса 3 (но не включая его!).
Примечание. Индексирование в Python начинается с 0, поэтому первый элемент имеет индекс 0, второй элемент имеет индекс 1 и так далее.
Если вы хотите вывести все элементы, вы можете использовать один из двух следующих способов:
Итак, мы поняли, как использовать срезы для вывода всех элементов, содержащихся в списке.
Теперь, давайте разберемся, как же перевернуть наш список, используя срезы. Всё просто – давайте добавим шаг. И точно так же, как и с функцией range() , сделаем его отрицательным.
В данном случае мы используем два двоеточия для вывода всех элементов от начала и до самого конца и отрицательный шаг для того, чтобы элементы были в обратном порядке.
Рассмотрим на примере, как это работает:
В этом случае мы создаем новый список my_list2 , при этом порядок исходного списка не изменяется.
Как перевернуть список в Python с помощью функции reversed()
Важно! Не путайте функцию reversed() с методом .reverse() !
Встроенная функция reversed() меняет порядок элементов списка на противоположный и позволяет нам обращаться к каждому элементу по отдельности.
К примеру, возьмем следующий список my_list :
Функция reversed() принимает список в качестве аргумента и возвращает нам исходные элементы, только в обратном порядке.
Если вы хотите сохранить возвращаемое значение из функции reversed() для дальнейшего использования, то нужно преобразовать результат в список с помощью функции list() . Далее необходимо присвоить получившееся выражение переменной, в нашем случае my_new_list .
Теперь в переменной my_new_list хранится перевёрнутый список my_list .
Важно заметить, что основное отличие метода .reverse() и функции reversed() заключается в том, что метод .reverse() меняет непосредственно исходный список. В то время как функция reversed() не изменяет сам исходный список, и полученное новое значение следует сохранять в новую переменную.
Заключение
Вот и все – теперь вы знаете основы работы с реверсированными списками в Python!
Мы подробно и на примерах разобрали, как перевернуть список в Python. Надеемся, что данная статья была вам полезной. Спасибо за чтение и успехов в написании кода!