Tags
 IOS SQL HTML C RUBY-ON-RAILS MYSQL ASP.NET DEVELOPMENT RUBY .NET LINUX SQL-SERVER REGEX WINDOWS ALGORITHM ECLIPSE VISUAL-STUDIO STRING SVN PERFORMANCE APACHE-FLEX UNIT-TESTING SECURITY LINQ UNIX MATH EMAIL OOP LANGUAGE-AGNOSTIC VB6

# Is using [::-1] in python to reverse a list O(1) space?

By : Yoco
Date : July 29 2020, 11:00 AM
I wish this help you You are right that some_list[::-1] creates a new list, and that that list will have n "slots", and thus need O(n) memory.
Furthermore in CPython [GitHub], an interpreter of Python, the .reverse() is done in O(1) memory. Indeed, if we look at the reverse method [GitHub], we see:
code :
``````/*[clinic input]
list.reverse
Reverse *IN PLACE*.
[clinic start generated code]*/

static PyObject *
list_reverse_impl(PyListObject *self)
/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
{
if (Py_SIZE(self) > 1)
reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Py_RETURN_NONE;
}``````
``````/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
static void
reverse_slice(PyObject **lo, PyObject **hi)
{
assert(lo && hi);

--hi;
while (lo < hi) {
PyObject *t = *lo;
*lo = *hi;
*hi = t;
++lo;
--hi;
}
}``````

Share :

## how to reverse a list with O(1) space and O(n) time?

By : MartinTilma
Date : March 29 2020, 07:55 AM
this one helps. Just read one of the following. It is the thing you're talking about.

By : Alex Zhao
Date : March 29 2020, 07:55 AM
Hope this helps since you're creating new instance of linked list - you will have 2 copies of list in memory. The list will contain references to objects, so if you want to count instances of objects - then you are safe and amount of additional memory is O(1). But list itself takes some memory, so if you count number of "cells" in lists - then yes, you have O(N) additional memory being used.

## Python Sorting list of tuples reverse by value and non-reverse by key (two different ways)

By : youhunt
Date : March 29 2020, 07:55 AM
may help you . The title is rather confusing but the question is rather straightforward. , In this specific case the problem is easy...
code :
``````L.sort(key = lambda x : (-x[1], x[0]))
``````

## Python 2.7 reverse a text by space character

By : Faiz
Date : March 29 2020, 07:55 AM
Does that help I'm assuming your newline character is \n and not /n as you've posted.

## reverse print an immutable linked list with less than O(n) space

By : user5580423
Date : March 29 2020, 07:55 AM
hope this fix your issue This is an O(n) time and O(sqrt(n)) space algorithm. In the second part of the post it will be extended to a linear time and O(n^(1/t)) space algorithm for an arbitrary positive integer t.
High-level idea: Split the list into sqrt(n) many (almost) equal-sized parts. Print the parts one after the other in reverse order using a naive linear-time, linear-space method, from the last to the first.