惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Project Zero
Project Zero
F
Fortinet All Blogs
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
S
SegmentFault 最新的问题
Blog — PlanetScale
Blog — PlanetScale
T
Tailwind CSS Blog
WordPress大学
WordPress大学
Engineering at Meta
Engineering at Meta
S
Schneier on Security
N
News and Events Feed by Topic
N
News | PayPal Newsroom
H
Help Net Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
The Exploit Database - CXSecurity.com
Attack and Defense Labs
Attack and Defense Labs
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
A
About on SuperTechFans
AWS News Blog
AWS News Blog
S
Secure Thoughts
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
C
Cybersecurity and Infrastructure Security Agency CISA
V2EX - 技术
V2EX - 技术
Recorded Future
Recorded Future
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
MyScale Blog
MyScale Blog
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
人人都是产品经理
人人都是产品经理
Latest news
Latest news
C
Cyber Attacks, Cyber Crime and Cyber Security
大猫的无限游戏
大猫的无限游戏
The Last Watchdog
The Last Watchdog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
月光博客
月光博客
H
Hacker News: Front Page
P
Proofpoint News Feed
N
News and Events Feed by Topic
H
Heimdal Security Blog
L
Lohrmann on Cybersecurity
有赞技术团队
有赞技术团队
L
LangChain Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
Python Reverse a List
2025-04-13 · via Stonecharioteer on Tech

There are a couple of ways to reverse a list in python:

1
2
3
4
5
my_list = [1,2,3,"apples","banana","fish","chicken"]
reverse_list_one = my_list[::-1]
reverse_list_one = reversed(my_list)
reverse_list_zero = my_list
reverse_list_zero.reverse()

Of these three ways, I prefer using reversed because it is readable and there’s no ambiguity about whether it does it in place or not. It should be obvious to most people that .reverse() reverses a list in place, but I prefer the verbosity of the method that returns a reversed list. It’s a stylistic choice.

The [::-1] syntax though is unreadable unless you know where it comes from. The syntax is List[start:stop_at:step_count]. This can be used to collect items of a list in a specific way. You could use it to collect all the alternate items in a list through my_list[::2], or every third item from the first to the seventh index, through my_list[0:7:2] (If you don’t want to include the last item, remember that python’s list intervals are half-open).

So [::-1] means collect all the items in this array but move through it -1 items at a time, meaning, start with the last item first and move backwards.

But which one of these is faster? We can use the timeit module to test this out.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import timeit
import random

my_list = [random.randrange(10**6) for _ in range(10**3)]

trial_1 = timeit.timeit("reversed(my_list)", number=10**4, globals=dict(my_list=my_list))
print(trial_1)
my_list_1 = my_list
trial_2 = timeit.timeit("my_list_1.reverse()", number=10**4, globals=dict(my_list_1=my_list_1))
print(trial_2)
trial_3 = timeit.timeit("my_list[::-1]", number=10**4, globals=dict(my_list=my_list))
print(trial_3)

This attempts to reverse a list of a thousand numbers ranging from 0 to a million ten thousand times. On my X13 Flow laptop and with python 3.12.3 this gets me the following output:

0.0005502169997271267
0.0013474229999701492
0.012336962999597745

I’m fairly surprised myself that reversed is the fastest way to reverse a list in Python. I half expected to tell you that it’d be the list notation syntax. And it’s faster than the in-place method, which isn’t surprising since it’s not trying to move things around to save memory. This StackOverflow answer shows that it’s creating an iterator and not returning a list like the list notation syntax would, so using list(reversed(my_list)) would be a fairer comparison.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import timeit
import random

my_list = [random.randrange(10**6) for _ in range(10**3)]

trial_1 = timeit.timeit("reversed(my_list)", number=10**4, globals=dict(my_list=my_list))
my_list_1 = my_list
trial_2 = timeit.timeit("my_list_1.reverse()", number=10**4, globals=dict(my_list_1=my_list_1))
trial_3 = timeit.timeit("my_list[::-1]", number=10**4, globals=dict(my_list=my_list))
trial_4 = timeit.timeit("list(reversed(my_list))", number=10**4, globals=dict(my_list=my_list))
print(f"""
{ trial_1= }
{ trial_2= }
{ trial_3= }
{ trial_4= }
""")

Now we get a more realistic solution.

 trial_1= 0.0005320420000316517
 trial_2= 0.0013524949999919045
 trial_3= 0.011964209999860032
 trial_4= 0.032413619000180915

Honestly though, this doesn’t prove anything. If I needed a reversed list to iterate over, the iterator approach with reversed is the best way to do it. If I need an in-memory version of it, the list notation syntax is clean. In-place reversal is useful only if I’m completely sure I would like to reverse the list in place. This is useful when the list is perhaps an attribute of a class, for example.