Recent from talks
Contribute something
Nothing was collected or created yet.
Zen of Python
View on Wikipedia
The Zen of Python is a collection of 19 "guiding principles" for writing computer programs that influence the design of the Python programming language.[1] Python code that aligns with these principles is often referred to as "Pythonic".[2]
Software engineer Tim Peters wrote this set of principles and posted it on the Python mailing list in 1999.[3] Peters' list left open a 20th principle "for Guido to fill in", referring to Guido van Rossum, the original author of the Python language. The vacancy for a 20th principle has not been filled.
Peters' Zen of Python was included as entry number 20 in the language's official Python Enhancement Proposals and was released into the public domain.[4] It is also included as an Easter egg in the Python interpreter, where it can be displayed by entering import this.[1][4][a]
In May 2020, Barry Warsaw (developer of GNU Mailman) used it as the lyrics to a song.[5][6]
Principles
[edit]The principles are listed as follows:[b]
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.[c]
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than right now.[d]
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea – let's do more of those!
Being Pythonic
[edit]One of the principles, "There should be one-- and preferably only one --obvious way to do it", can be referenced as the "Pythonic" way.[8] The official definition of "Pythonic" is:[2][e]
An idea or piece of code which closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages. For example, a common idiom in Python is to loop over all elements of an iterable using a
forstatement. Many other languages don’t have this type of construct, so people unfamiliar with Python sometimes use a numerical counter instead:for i in range(len(food)): print(food[i])As opposed to the cleaner, Pythonic method:
for piece in food: print(piece)
Code that is difficult to understand or reads like a rough transcription from another programming language is called unpythonic.[9]
In practice
[edit]Since the release of the Zen of Python, there has been research done on its effectiveness and actual use among developers. Despite the difference in interpretation between beginners and experienced Python programmers, interviews among 13 Python programmers of varying skill show that the Zen of Python "positively influences the way developers write and talk about code".[8] Researchers extended this case study to explore the use of Python idioms on GitHub repositories, and found that the usage of "Pythonic idioms"[f] increased over time.[10] Writing Python code that aligns with the Zen of Python may save memory and run time of Python programs.[11] The desire to write in Pythonic code has led to refactoring tools to help programmers achieve this goal.[12][13]
See also
[edit]Notes
[edit]- ^ The source code for the Zen of Python can be found on Github.
- ^ Wikipedia links below are added for further reference and understanding, and were not explicitly linked in the Zen of Python
- ^ The formatting of the dashes in this line and the final is purposely inconsistent, in reference to the varying formatting conventions.[7]
- ^ In the interpreter easter egg, this is written as "Although never is often better than *right* now." This follows a longstanding convention of plain-text communication — in which common formatting features are often impossible — where emphasis is represented with asterisks.
- ^ This definition below is directly quoted to preserve its definition. So as is, it is not self-contained valid Python to run without errors.
- ^ A list of their Pythonic idioms can be found here https://slimshadyiam.github.io/ZenYourPython/
References
[edit]- ^ a b Reitz, Kenneth (2011–2019). "Code Style". The Hitchhiker’s Guide to Python. § Zen of Python. Retrieved March 26, 2019.
- ^ a b "Glossary". Python Documentation. Retrieved 2024-02-07.
- ^ Peters, Tim (June 4, 1999). "The Python Way". Python Software Foundation. Retrieved March 26, 2019.
- ^ a b Peters, Tim (August 19, 2004). "PEP 20—The Zen of Python". Python Software Foundation. Retrieved March 26, 2019.
- ^ Warsaw, Barry (10 May 2020). "The Zen of Python". We Fear Change. Archived from the original on 2020-06-03.
- ^ Warsaw, Barry (23 May 2020). The Zen of Python. YouTube. The Zbwedicon. Archived from the original on 2021-12-11. Archived 2020-06-03 at the Wayback Machine
- ^ "Issue 3364: An ortographical typo in Zen of Python text - Python tracker". bugs.python.org.
- ^ a b Alexandru, Carol V.; Merchante, José J.; Panichella, Sebastiano; Proksch, Sebastian; Gall, Harald C.; Robles, Gregorio (2018-10-24). "On the usage of pythonic idioms" (PDF). Proceedings of the 2018 ACM SIGPLAN International Symposium on New Ideas, New Paradigms, and Reflections on Programming and Software (PDF). Onward! 2018. New York, NY, USA: Association for Computing Machinery. pp. 1–11. doi:10.1145/3276954.3276960. ISBN 978-1-4503-6031-9. OCLC 1362712424. S2CID 53057358. Archived from the original on 2024-03-24. Retrieved 2024-02-19.
{{cite book}}: CS1 maint: bot: original URL status unknown (link) - ^ "Code Style – The Hitchhiker's Guide to Python". docs.python-guide.org. Archived from the original on 27 January 2021. Retrieved 20 January 2021.
- ^ Farooq, Aamir; Zaytsev, Vadim (2021-11-22). "There is more than one way to zen your Python". Proceedings of the 14th ACM SIGPLAN International Conference on Software Language Engineering. SLE 2021. New York, NY, USA: Association for Computing Machinery. pp. 68–82. doi:10.1145/3486608.3486909. ISBN 978-1-4503-9111-5.
- ^ Leelaprute, Pattara; Chinthanet, Bodin; Wattanakriengkrai, Supatsara; Kula, Raula Gaikovina; Jaisri, Pongchai; Ishio, Takashi (2022-10-20). "Does coding in Pythonic zen peak performance?: Preliminary experiments of nine Pythonic idioms at scale". Proceedings of the 30th IEEE/ACM International Conference on Program Comprehension. ICPC '22. New York, NY, USA: Association for Computing Machinery. pp. 575–579. doi:10.1145/3524610.3527879. ISBN 978-1-4503-9298-3.
- ^ Zhang, Zejun; Xing, Zhenchang; Xia, Xin; Xu, Xiwei; Zhu, Liming (2022-07-12), Making Python Code Idiomatic by Automatic Refactoring Non-Idiomatic Python Code with Pythonic Idioms, arXiv:2207.05613
- ^ Phan-udom, Purit; Wattanakul, Naruedon; Sakulniwat, Tattiya; Ragkhitwetsagul, Chaiyong; Sunetnanta, Thanwadee; Choetkiertikul, Morakot; Kula, Raula Gaikovina (2020-09-05), Teddy: Automatic Recommendation of Pythonic Idiom Usage For Pull-Based Software Projects, arXiv:2009.03302
External links
[edit]Zen of Python
View on Grokipediaimport this displays the full list of aphorisms. The source code of the this module is an encoded poem that, when decoded, reveals the implementation in a playful format.[1] This feature has made it a widely referenced cultural touchstone in the Python community, influencing coding standards, style guides like PEP 8, and educational resources since its inception.[1]
The Aphorisms
The complete list of 19 aphorisms from PEP 20 is as follows:- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one— and preferably only one —obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than right now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea— let's do more of those
Origins and Development
Authorship and Motivation
The Zen of Python was authored by Tim Peters, a prominent Python core developer renowned for his contributions to the language's implementation, including the creation of the timsort hybrid sorting algorithm in 2002, which became the default sorting method for Python lists due to its efficiency on real-world data.[2] Peters, a long-time contributor to Python since the 1990s, formalized these principles to encapsulate the informal philosophy guiding the language's evolution.[1] The motivation for the Zen originated in a June 1999 post by Peters on the Python mailing list (python-list), where he outlined "The Way of Python" as a set of aphorisms distilling key design ideas amid community discussions on Python's direction.[3] The aphorisms were intended to poetically capture Python's core ethos, leaving the 20th principle open "for Guido to fill in," honoring the language's Benevolent Dictator for Life, Guido van Rossum.[1] At its heart, the Zen emphasized Python's commitment to readability and simplicity as a deliberate counterpoint to the verbosity of languages like Java and the dense, punctuation-heavy syntax of Perl, which often prioritized flexibility over clarity.[4] Van Rossum's vision, channeled by Peters, sought to make code as executable as natural language, fostering a community-driven philosophy amid early 2000s debates on language guidelines that shaped Python's growth.[4] This focus addressed frustrations with more complex contemporaries, promoting an "elegant" approach where simplicity enables practical problem-solving without unnecessary ornamentation.[1]Publication and Timeline
The Zen of Python traces its origins to June 4, 1999, when Tim Peters, a prominent early contributor to Python's development, posted an initial draft of 19 aphorisms to the python-list mailing list, framing them as "The Python Way" to capture the language's idiomatic spirit.[3] This informal proposal laid the groundwork for what would become a cornerstone of Python's philosophy, though it remained outside official channels for several years. On August 19, 2004, Peters submitted PEP 20 to the Python Enhancement Proposals (PEPs) repository, formally titling it "The Zen of Python" and presenting the aphorisms as a distillation of Python's design principles.[1] The PEP was quickly posted for discussion on August 22, 2004, and achieved active status without revisions. It was integrated into the official Python 2.4 documentation upon that version's release on November 30, 2004, marking its entry into the language's canonical resources.[1] [5] PEPs function as Python's governance framework for proposing, discussing, and documenting enhancements, ranging from technical features to process improvements and informational guides, with oversight from core maintainers and the Steering Council.[6] Distinct from standards-track PEPs that drive code changes, PEP 20 stands as a purely informational artifact, offering philosophical guidance rather than mandating implementations, and it has undergone no modifications since its creation.[6] [1] This stability has ensured its unchanged inclusion across all subsequent releases, from Python 2.5 through Python 3.x versions up to 3.14 in 2025.[1]Core Principles
Complete List of Aphorisms
The Zen of Python, a set of guiding principles for Python's design, is presented as an Easter egg accessible by executingimport this in a Python interpreter. This command outputs the following text, authored by Tim Peters:[1]
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
import this in the Python shell.[1]
Thematic Structure and Interpretation
The principles of the Zen of Python can be grouped into several overarching themes that reflect core aspects of Python's design philosophy. One prominent theme is readability, encapsulated in aphorisms such as "Readability counts," which underscores the language's emphasis on code that is easy to understand and maintain for human readers.[1] This theme prioritizes clarity in syntax and structure to facilitate collaboration and long-term code evolution.[7] Another key theme revolves around simplicity versus complexity, highlighted by paired aphorisms like "Simple is better than complex" and "Complex is better than complicated." These encourage developers to favor straightforward solutions where possible, while acknowledging that necessary complexity should remain elegant rather than convoluted.[1] For instance, "Flat is better than nested" promotes shallower code hierarchies to enhance comprehension, though it allows for essential nesting in cases like function definitions or data structures.[7] In contrast, "Sparse is better than dense" advises against overly compact code, such as excessive one-liners, to avoid obscuring intent.[8] Practicality forms a third theme, best illustrated by "Although practicality beats purity," which permits deviations from strict rules when they yield more effective outcomes, balancing idealism with real-world utility.[1] This principle supports flexible application of the guidelines, recognizing that rigid adherence might hinder problem-solving.[8] Relatedly, "Special cases aren't special enough to break the rules" reinforces consistency unless practicality demands otherwise.[1] A distinct theme addresses namespaces, affirmed in the aphorism "Namespaces are one honking great idea -- let's do more of those!" This advocates for modular organization through scopes and modules to prevent naming conflicts and promote scalable code architecture.[1] Several principles offer specific interpretations that guide Python's avoidance of overly clever or "magical" constructs. "Explicit is better than implicit" discourages hidden behaviors, such as automatic type coercion or undisclosed side effects, favoring transparent mechanisms like explicit imports or type annotations to reduce surprises and errors.[1][7] This contrasts with languages that rely on inference, promoting code where intent is immediately evident. The Zen of Python lists only 19 aphorisms, leaving a 20th unwritten, which implies inherent flexibility in their application—developers are encouraged to adapt the principles contextually rather than treat them as inflexible dogma.[1][7] Historical allusions enrich the principles, such as in "There should be one-- and preferably only one --obvious way to do it," which nods to Python creator Guido van Rossum's Dutch heritage via the follow-up "Although that way may not be obvious at first unless you're Dutch," while critiquing Perl's embrace of multiple approaches (TMTOWTDI).[1][7]Pythonic Programming
Defining Pythonic Code
Pythonic code refers to an approach in programming that adheres closely to the idioms and conventions of the Python language, as outlined in the Zen of Python (PEP 20).[9] This style emphasizes writing code that is idiomatic, readable, and efficient, while prioritizing clarity and simplicity over overly clever or complex solutions.[1] The guiding philosophy, captured in aphorisms such as "Beautiful is better than ugly" and "Readability counts," encourages developers to produce code that is easy for others to understand and maintain.[1] Key traits of Pythonic code include leveraging Python's built-in functions and standard library to promote conciseness and effectiveness. For example, opting for language constructs like list comprehensions over traditional loops aligns with the principle that "simple is better than complex," reducing boilerplate while preserving expressiveness.[1] Additionally, Pythonic practices discourage unnecessary abstraction, favoring direct and obvious methods—such as using built-in data types—over custom implementations that add unneeded layers, in line with "There should be one— and preferably only one— obvious way to do it."[1] In contrast, non-Pythonic code often appears overly verbose or obfuscated, diverging from these idioms and complicating comprehension. For instance, employing full class definitions for straightforward data representation, when a dictionary or namedtuple would provide sufficient structure, can introduce needless complexity and contradict the Zen's advocacy for explicitness and flat hierarchies.[9] Such approaches may rely on indirect mechanisms, like indexing lists instead of iterating directly over elements, which obscures intent and violates "explicit is better than implicit."[1] Theimport this module offers a practical way to access the Zen of Python, printing its aphorisms upon execution and serving as an immediate reference for developers to assess whether their code embodies these principles.[1] This accessibility reinforces the Zen's role as a foundational checklist for maintaining Pythonic standards in everyday coding.[1]
Practical Examples
To illustrate the application of Zen of Python principles in everyday coding, consider examples that transform common anti-patterns into more Pythonic alternatives, enhancing code quality without sacrificing functionality. These demonstrations draw from standard Python practices and highlight improvements in clarity and efficiency.[1] One key principle, "Simple is better than complex," favors concise expressions like list comprehensions over explicit loops for generating lists, as they reduce boilerplate while maintaining readability. For instance, to square numbers in a list of integers, a verbose approach might use a traditional for loop:numbers = [1, 2, 3, 4, 5]
squared = []
for num in numbers:
squared.append(num ** 2)
numbers = [1, 2, 3, 4, 5]
squared = []
for num in numbers:
squared.append(num ** 2)
numbers = [1, 2, 3, 4, 5]
squared = [num ** 2 for num in numbers]
numbers = [1, 2, 3, 4, 5]
squared = [num ** 2 for num in numbers]
def apply_discount(price):
return price * (1 - 0.15) # What is 0.15?
def apply_discount(price):
return price * (1 - 0.15) # What is 0.15?
DISCOUNT_RATE = 0.15
def apply_discount(price):
return price * (1 - DISCOUNT_RATE)
DISCOUNT_RATE = 0.15
def apply_discount(price):
return price * (1 - DISCOUNT_RATE)
def divide_numbers(a, b):
result = a / b
return result # Silently fails if b is 0
def divide_numbers(a, b):
result = a / b
return result # Silently fails if b is 0
def divide_numbers(a, b):
try:
return a / b
except ZeroDivisionError:
print("Error: [Division by zero](/page/Division_by_zero) is not allowed.")
return None
def divide_numbers(a, b):
try:
return a / b
except ZeroDivisionError:
print("Error: [Division by zero](/page/Division_by_zero) is not allowed.")
return None
# globals.py or single file
CONFIG = {"host": "localhost", "port": 8080}
user_data = []
def process_user(input_data):
user_data.append(input_data) # Global mutation
return CONFIG["host"]
# globals.py or single file
CONFIG = {"host": "localhost", "port": 8080}
user_data = []
def process_user(input_data):
user_data.append(input_data) # Global mutation
return CONFIG["host"]
# config.py
CONFIG = {"host": "localhost", "port": 8080}
# users.py
user_data = []
def process_user(input_data):
user_data.append(input_data)
return CONFIG["host"] # Imported as needed
# config.py
CONFIG = {"host": "localhost", "port": 8080}
# users.py
user_data = []
def process_user(input_data):
user_data.append(input_data)
return CONFIG["host"] # Imported as needed
from config import CONFIG) keeps namespaces distinct and reduces accidental overwrites. Modular structures like this promote reusability and limit variable scope, curbing side effects that lead to subtle bugs.[1]
In practice, these Pythonic refactorings significantly lower bug incidence and maintenance overhead in domains such as data analysis pipelines and web applications. For example, empirical analysis of Python projects reveals that adherence to modular and explicit coding patterns correlates with reduced maintenance costs.[12] Similarly, in Jupyter-based data analysis workflows, avoiding silent failures and verbose constructs cuts bug density by enabling quicker debugging.[13] For web apps built with frameworks like Django or Flask, such practices streamline updates and scalability, as clearer code facilitates team collaboration and reduces refactoring time by emphasizing readable, namespace-isolated components.
