Python Tricks: Sets, Calendar, Enumerate, Conditional Logic, Enum, and iPython
This article presents a collection of practical Python tips covering set operations, calendar calculations, the enumerate function with a start index, clean conditional handling using dictionaries and enums, and an introduction to iPython for interactive development, all illustrated with concise code examples.
Python provides many built‑in features that can simplify everyday coding tasks. This guide walks through several useful tricks.
1. Sets
Sets are unordered collections without duplicate elements. They are handy for extracting unique characters from a string or removing duplicates from a list.
<code>myword = "NanananaBatman"
set(myword)
# {'N', 'm', 'n', 'B', 'a', 't'}
mylist = ["a", "b", "c", "c"]
myset = set(mylist)
# {'a', 'b', 'c'}
for element in myset:
print(element)
mynewlist = list(myset)
# ['a', 'b', 'c']
</code>Note that converting back to a list may change the order because sets are unordered.
2. Calendar
The calendar module can return the weekday of the first day of a month and the number of days in that month via calendar.monthrange(year, month) . It also handles leap years and provides helper functions such as calendar.isleap and calendar.leapdays .
<code>import calendar
calendar.monthrange(2020, 12) # (1, 31)
calendar.monthrange(2024, 2) # (3, 29) # leap year
calendar.isleap(2024) # True
calendar.leapdays(2020, 2026) # 2
</code>You can compute the weekday for any day by combining the offset returned by monthrange with a list of weekday names.
<code>weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
offset = 3 # first weekday for Feb 2024
for day in range(1, 30):
print(day, weekdays[(day + offset - 1) % 7])
</code>3. Enumerate with a start index
The built‑in enumerate can accept a second argument to specify the starting index, which is useful when you need a custom offset.
<code>mylist = ['a', 'b', 'd', 'c', 'g', 'e']
for i, item in enumerate(mylist, 16):
print(i, item)
# 16 a
# 17 b
# 18 d
# 19 c
# 20 g
# 21 e
</code>4. Clean conditional handling
When many conditions are involved, using a dictionary of handlers or an Enum improves readability. The example shows a simple status‑handling system using an IntEnum and a handler map.
<code>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 status
</code>5. Enum module
The enum module provides Enum , IntEnum , Flag , and IntFlag . Enums give named constants with readable .name and .value attributes and can be instantiated by value or name.
<code>from enum import Enum, IntEnum
class MyEnum(Enum):
FIRST = "first"
SECOND = "second"
THIRD = "third"
class MyIntEnum(IntEnum):
ONE = 1
TWO = 2
THREE = 3
MyEnum.FIRST.value # 'first'
MyIntEnum.ONE == 1 # True
</code>Enums are especially helpful in medium‑size codebases for managing constant values and can be integrated with Django choices for localization.
6. iPython
iPython is an enhanced interactive Python shell. Install it with pip install ipython and enjoy features like tab completion, system command shortcuts, and richer output formatting.
<code>pip install ipython
# After starting iPython you will see:
# In [1]:
</code>For more details, refer to the official documentation.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.