I need to traverse a list backwards. I read about xrange() and reversed(). Which one is more expensive?
2
There are 2 best solutions below
2
dsh
On
xrange() produces a sequence of numbers. You can then use those numbers as list indices if you want, or you can use them for anything where you want those numbers.
for i in xrange( len(l)-1, -1, -1):
item = l[i]
print item
reversed() produces the items from something that has a length and can be indexed.
for item in reversed(l):
print item
I would use reversed() because it makes you code shorter, simpler, clearer, and easier to write correctly.
Related Questions in PYTHON
- new thread blocks main thread
- Extracting viewCount & SubscriberCount from YouTube API V3 for a given channel, where channelID does not equal userID
- Display images on Django Template Site
- Difference between list() and dict() with generators
- How can I serialize a numpy array while preserving matrix dimensions?
- Protractor did not run properly when using browser.wait, msg: "Wait timed out after XXXms"
- Why is my program adding int as string (4+7 = 47)?
- store numpy array in mysql
- how to omit the less frequent words from a dictionary in python?
- Update a text file with ( new words+ \n ) after the words is appended into a list
- python how to write list of lists to file
- Removing URL features from tokens in NLTK
- Optimizing for Social Leaderboards
- Python : Get size of string in bytes
- What is the code of the sorted function?
Related Questions in LIST
- Difference between list() and dict() with generators
- python how to write list of lists to file
- SML - Find same elements in a string
- How to divide list item by list item from another list using Python?
- How to get a certain element in a list of lists?
- How to read in numbers from n lines into a Scala list?
- Create a list of sequential monthly dates in PHP given initial date and quantity
- Python elegant way to sort numerically named directories
- sorting all data on multiple pages by clicking on its header
- List item keeps same memory address following sort/copy
- How to convert Hibernate List to String?
- using a for loop to compare lists
- How to keep track of word count in text file
- Running multiprocessing on two different functions in Python 2.7
- How do you fuse string items from two lists into new elements of a new list?
Related Questions in TRAVERSAL
- Haskell lens: let binding of Traversal'
- Traversing with XPath?
- How to traverse all nodes of clang AST?
- Smallest cost traversal of an array
- Recurse through selected level of subdirectories
- Timeout on Neo4j traversal framework
- Stop Cypher traversal when where condition on reduce() can no longer be satisfied
- _.findWhere array-object within array-object property equals something
- How to traverse through an editable UITextView String to check for certain words in Swift
- Fastest way to traverse all edge of a directed attributed graph which stores in adjacency matrix
- modify vertex or edges attributes with a Traversal Object in ArangoDB?
- find path between vertices using edge properties in OrientDB
- Is there any way to get column value on the basis of row number?
- Traversal on different criteria using iterator pattern
- Traverse a list of tuples containg a string and list in python
Related Questions in XRANGE
- xrange as an iterator and chunking
- xrange vs iterators python
- list out of range when going through an array checking for duplicates in python 2.7
- About memory efficiency: range vs xrange, zip vs izip
- Highchart gantt/xrange chart styling with data not plotting aligned to labels
- Highchart xrange chart looks different in React code than in javascript code and does not take yAxis categories as it does in javascript code snippet
- why is xrange able to go back to beginning in Python?
- Why the xrange function in the library code still works?
- Accessing xrange internal structure
- xrange generating strings? I don't get it
- Core plot : how to change plotSpace.xRange dynamically when device orientation change?
- How to fix" xrange() arg 3 must not be zero" error in python using parallel programming?
- Can highcharts xrange labels be shown only if they fit the box?
- How to chunk up an interval in Python?
- Gnuplot: how to set xrange with set xtics time?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
You can use Python's timeit library to time things like this. You don't say what kind of list you have, so I am assuming a simple list of strings. First I create a list 100 items long and then time both:
This gives the following result:
As you can see, in this example
reversed()is a bit faster.