I’m using Python 3.2.3. What’s the fastest way to iterate over a list in reverse? [::-1], reversed, list.reverse() or maybe some other way? I’m dealing with a list of about 5e6 elements or so, so I really need to avoid copying the list.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Conclusion: reversed() is marginally faster than l.reverse() on a list with 100000 items.
This of course is even more true if you don’t actually loop over the whole list, and it stops being true if you use the list more than once.
l[::-1]is outdated since 2.4 that introducedreversed().