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
- How to store a date/time in sqlite (or something similar to a date)
- Instagrapi recently showing HTTPError and UnknownError
- How to Retrieve Data from an MySQL Database and Display it in a GUI?
- How to create a regular expression to partition a string that terminates in either ": 45" or ",", without the ": "
- Python Geopandas unable to convert latitude longitude to points
- Influence of Unused FFN on Model Accuracy in PyTorch
- Seeking Python Libraries for Removing Extraneous Characters and Spaces in Text
- Writes to child subprocess.Popen.stdin don't work from within process group?
- Conda has two different python binarys (python and python3) with the same version for a single environment. Why?
- Problem with add new attribute in table with BOTO3 on python
- Can't install packages in python conda environment
- Setting diagonal of a matrix to zero
- List of numbers converted to list of strings to iterate over it. But receiving TypeError messages
- Basic Python Question: Shortening If Statements
- Python and regex, can't understand why some words are left out of the match
Related Questions in LIST
- How to give the player the ability to choose a grid in Battleship?
- Sorting a List by its property renames all the objects in the List
- Replace NA in list of dfs in certain columns and under certain conditions
- Why does print(list.sort()) result in None?
- How to distribute the sum of several numbers similarly?
- Random getting value from a range or a specific value
- drop down list to decide which range my graph will plot
- List > numpy.ndarray using np.array(list) not working in class __init__ . Problem with numpy?
- Creating an efficent and time-saving algorithm to find difference between greater than and lesser than combination
- Flutter: How to add items and save it in local storage?
- Why my code is working on everything except one instance?
- Why does the following code detect this matrix as a non-singular matrix?
- How do I convert a list of chars into a list of strings in F#?
- Going back to an earlier index in list iteration
- If the element(s) in the first list equal element(s) of the second list, replace with element(s) of the third list
Related Questions in TRAVERSAL
- Why is my traversing in BST not showing the results like the sample output?
- Top View Of Binary Tree Depth First Search Using TreeMap
- How to parse a nested XML using PowerShell
- How to convert an array of text segments into DOM tree object?
- Problem Working with Arrays in Pharo 11.0
- Finding the least costly cycle on a graph where at least one node out of multiple node subsets must be met and each edge has a cost
- Iterative Postorder Traversal of a Binary Tree
- A common lisp subst variant that can traverse defstructs
- Finding leftmost nodes in every level of a tree
- Inorder Binary Tree Traversal
- Python IDDFS missing potential results
- malformed tree nesting when traversing, what's the solution?
- Node Traversal to Java String Set?
- PHP - Object or Array for Variable Number of Values per Item?
- Traversal with .closest() fails
Related Questions in XRANGE
- 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
- R highchart xrange charts for 24hour time period
- gnuplot - How do I change xrange when changing x-axis scale?º
- Python3 and pypdf
- gnuplot - set xrange with date [1:31]
- Highchart for Android library x-range chart How to use dynamic y-axis data
- Why the xrange function in the library code still works?
- trying to use highchart xrange to display large number of categories
- Gnuplot: how to set xrange with set xtics time?
- How to set xrange on command line in gnuplot
- How to dynamically create timeline chart on click of x-range chart in highcharts angular
- bokeh categorical vbar, x_range not working
- How does does xrange let you test membership?
- Problem with xrange in fill transparent plot
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 # Hahtags
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.