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

推荐订阅源

Vercel News
Vercel News
SecWiki News
SecWiki News
WordPress大学
WordPress大学
小众软件
小众软件
博客园 - 司徒正美
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Visual Studio Blog
Y
Y Combinator Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
K
Kaspersky official blog
T
The Exploit Database - CXSecurity.com
腾讯CDC
Scott Helme
Scott Helme
I
InfoQ
Cyberwarzone
Cyberwarzone
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Security Latest
Security Latest
The Register - Security
The Register - Security
Project Zero
Project Zero
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
A
Arctic Wolf
C
Cisco Blogs
L
LINUX DO - 热门话题
P
Privacy International News Feed
IT之家
IT之家
U
Unit 42
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Palo Alto Networks Blog
F
Full Disclosure
宝玉的分享
宝玉的分享
Simon Willison's Weblog
Simon Willison's Weblog
L
Lohrmann on Cybersecurity
Google DeepMind News
Google DeepMind News
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Hacker News: Front Page
Know Your Adversary
Know Your Adversary
PCI Perspectives
PCI Perspectives
Hugging Face - Blog
Hugging Face - Blog
AWS News Blog
AWS News Blog
MongoDB | Blog
MongoDB | Blog
S
Schneier on Security
Recent Announcements
Recent Announcements
Forbes - Security
Forbes - Security
Cisco Talos Blog
Cisco Talos 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.