Master Python Essentials: Sets, Calendars, Enums, and More
This article presents practical Python tricks—including set operations, calendar calculations, enumerate usage with custom start indices, clean if‑else handling via enums, the enum module itself, and iPython basics—providing concise examples and explanations to help developers write more efficient and readable code.
01. Sets
Developers often forget that Python has a built‑in set type, which stores an unordered collection of unique elements. Mastering sets can simplify many tasks, such as extracting unique letters from a word.
myword = "NanananaBatman"
set(myword) # {'N', 'm', 'n', 'B', 'a', 't'}Sets also make it easy to obtain a list of unique items from another list.
mylist = ["a", "b", "c", "c"]
myset = set(mylist) # {'a', 'b', 'c'}
for element in myset:
print(element)
mynewlist = list(myset) # ['a', 'b', 'c']Note that the order of elements may change when converting between list and set.
02. Calendar
When working with dates, you often need to know how many days a month contains or what weekday a month starts on. The calendar module provides convenient functions for these tasks.
import calendar
calendar.monthrange(2020, 12) # (1, 31) # weekday, number of days
calendar.monthrange(2024, 2) # (3, 29) # leap year handlingYou can map the returned weekday index to a name:
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
weekday_index, days = calendar.monthrange(2024, 2)
print(weekdays[weekday_index]) # ThursdayThe module also offers helpers for leap‑year checks:
calendar.isleap(2024) # True
calendar.leapdays(2020, 2026) # 203. Enumerate with a Start Index
The enumerate function can accept a second argument to specify the starting index.
mylist = ['a', 'b', 'd', 'c', 'g', 'e']
for i, item in enumerate(mylist, 16):
print(i, item)
# Output: 16 a, 17 b, 18 d, 19 c, 20 g, 21 e04. Clean If‑Else Logic Using Enums
For many conditions, mapping status values to handler functions via an Enum makes the code cleaner and more maintainable.
from enum import IntEnum
class StatusE(IntEnum):
OPEN = 1
IN_PROGRESS = 2
CLOSED = 3
def handle_open_status():
print('Handling open status')
def handle_in_progress_status():
print('Handling in‑progress status')
def handle_closed_status():
print('Handling closed status')
handlers = {
StatusE.OPEN.value: handle_open_status,
StatusE.IN_PROGRESS.value: handle_in_progress_status,
StatusE.CLOSED.value: handle_closed_status,
}
def handle_status_change(status):
if status not in handlers:
raise Exception(f'No handler for status: {status}')
handlers[status]()
handle_status_change(StatusE.OPEN.value) # Handling open status05. The Enum Module
The enum module provides Enum and IntEnum for defining symbolic constants.
from enum import Enum, IntEnum
class MyEnum(Enum):
FIRST = "first"
SECOND = "second"
THIRD = "third"
class MyIntEnum(IntEnum):
ONE = 1
TWO = 2
THREE = 3
print(MyEnum.FIRST.value) # 'first'
print(MyIntEnum.ONE == 1) # TrueEnums are especially useful in medium‑sized codebases for managing constants and can be integrated with Django choices.
06. iPython
iPython is an enhanced interactive Python shell. Install it with pip and start using it for richer command‑line experiences.
pip install ipython
# After launching, you will see a prompt like:
In [1]:iPython supports system commands, tab completion, and command history, making it a valuable tool for rapid experimentation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
