Python reverse() vs [::-1] slice performance [duplicate]
2024/11/19 2:33:10
Python provides two ways to reverse a list:
List slicing notation
['a','b','c'][::-1] # ['c','b','a']
Built-in reversed() function
reversed(['a','b','c']) # ['c','b','a']
Are there any relevant differences in implementation/performance, or scenarios when one is preferred over the other?
Answer
The slicing operator constructs a new list in memory, which has implications on both memory and runtime.
reversed, on the other hand, returns an iterator which simply yields items one after another from the original list in reversed order. It does not allocate any additional memory.
So if all you're doing is iterating over the list in reverse and there's no need to construct a new (for example if you need to mutate it), then I'd say go for reversed.
I would like to use Facebook Credits with my Django Application.In the Facebook Credits documentation, there is only a sample for the callback page in PHP (https://developers.facebook.com/blog/post/489…
I have a python list in which look like this:my_list = [OFAC\n, Social Media Analytics\n, Teaching Skills\n, Territory...\n, Active Directory...\n, Business Research\n, Call Center...\n, Treatment of d…
The following works well but Id like to make it faster. The actual application could process Tuple1 and Tuple2 each with 30,000 elements and 17 nested sequences per element. I see numerous questions …
Full error: line 10, in <module>colour = play()
NameError: name play is not definedI cant seem to find a reason for this issue anywhere on here. I am trying to assign the returned string to the v…
i have a problem with Django:
I cant show the data from mysql database in the table. I see the error "Exception Value: unhashable type: dict"
This is my code:
views.py:List_of_date=El.objects…
Im following a book tutorial and its telling me to install python3.3 with the command linesudo apt-get install python3.3however Im getting errorsUnable to locate package python3.3
Couldnt find any pack…
This question already has answers here:ImportError: cannot import name _ColumnEntity from sqlalchemy.orm.query(5 answers)ImportError: cannot import name _ColumnEntity Ubuntu20.10 [duplicate](1 answer)C…
The following code fails to run.It goes through a CSV file and retrieves the values and formats them in a array of tuples (a insert query) to be used later.
Problem is the csv last column is sometimes …
I am struggling with a program to tell whether a created disk touches the edge of a predefined box. The parser keeps saying things such asNameError: global name disksdescription is not defined
Warning…
I have a sample of a data frame which looks like this: +---+--------------------------------------------------------------------------------------+---------------+--------------------------------------…