Login
You're viewing the code4lib.social public feed.
  • Dec 23, 2025, 5:32 AM

    @futzle Walrus operators in Python are pretty weird, and everybody loves generator expressions, right?:

    data = [
    ("first", "a", "partridge in a pear tree"),
    ("second", "Two", "turtle doves"),
    ("third", "Three", "french hens"),
    ("fourth", "Four", "calling birds"),
    ("fifth", "Five", "golden rings"),
    ("sixth", "Six", "geese a-laying"),
    ("seventh", "Seven", "swans a-swimming"),
    ("eighth", "Eight", "maids a-milking"),
    ("ninth", "Nine", "ladies dancing"),
    ("tenth", "Ten", "lords a-leaping"),
    ("eleventh", "Eleven", "pipers piping"),
    ("twelfth", "Twelve", "drummers drumming"),
    ]
    for x in (
    gift_list := f"On the {ith} day of Christmas, my true love gave to me\n" + f"{count} {gift}\n" + ("" if ith == "first" else "And " + gift_list.split("\n")[-2] + "\n" if ith == "second" else '\n'.join(gift_list.split("\n")[1:]))
    for ith, count, gift in data
    ):
    print(x)

    💬 1🔄 0⭐ 0

Replies

  • Dec 23, 2025, 5:33 AM

    @futzle Somewhat cleaner / easier to understand version:

    foo = [
    (gift_list := [f"{count} {gift}"] if ith == "first" else [f"{count} {gift}"] + ["And " + gift_list[-1]] if ith == "second" else [f"{count} {gift}"] + gift_list,
    f"On the {ith} day of Christmas, my true love gave to me\n" + "\n".join(gift_list) + "\n\n")
    for ith, count, gift in data
    ]

    for x in foo:
    print(x[1])

    💬 0🔄 0⭐ 0