How to annotate *args in #Python? Just set the elements' type; we know it's a tuple:
def mysum(*args:int) -> int:
total = 0
for n in args:
total += n
return total
Normally, tuples contain different types. In args, we assume all values have the same type.
Posts by Reuven M. Lerner
Classic use of #Python's *args:
def mysum(*args):
total = 0
for n in args:
total += n
return total
Invoke it with separate int arguments:
mysum(10, 20, 30, 40, 50)
and *not* with a list containing ints:
mysum([10, 20, 30, 40, 50]) # Error!
Want your #Python function to take any number of positional args? Use *args:
- Can be any name, but args is traditional
- The * is only in the function definition
- It's a tuple
- Don't grab elements by index; iterate over them
- It might be empty
- Pronounce it "splat args"
Changing your clocks this weekend? Or did you do so a few weeks ago? Or maybe you never do?
In the latest Bamboo Weekly, we use #Python #Pandas to see which countries observe DST, and for how long each year.
Check it out: buff.ly/xH221g4
How are arguments assigned to parameters when calling a #Python function? There are two ways:
- Positional, based on order
- Keyword, i.e., name=value, assigned by name
Want to mix and match? Fine, but all positional must come before all keyword:
myfunc(10, 20, c=30)
To stop people from doing this, lazy import won't be allowed inside functions.
Every import in #Python executes the module, from start to finish.
Meaning? Big modules slow down your program's startup time.
Coming in Python 3.15 this October: "lazy import", which delays the load until a name is used:
lazy import MODULE
lazy from MODULE import NAME
Mutable builtins in #Python cannot be dict keys. But your (mutable) classes can!
class C:
def __init__(self, x):
self.x = x
c = C(10)
d = {c:10} # No error!
print(d[c]) # prints 10
You can't use a list as a #Python dict key:
mylist = ['a', 'b']
d = {mylist: 10} # TypeError!
Why not? Dicts run "hash" on a key to choose a pair's storage location. To avoid pairs getting lost, mutable builtins (list, set, dict) cannot be used as dict keys.
A #Python #Pandas column contains comma-separated values. How can you get the first of those?
First, break each string into a list:
df['x'].str.split(',')
Then use .str[0] to grab the first element from the resulting list:
df['x'].str.split(',').str[0]
Want to check whether a #Python #Pandas string series only contains digits? Use str.isdigit:
df['x'].str.isdigit()
This returns a boolean series, with df's index. You can then convert the digit-containing strings to integers:
df.loc[pd.col('x').str.isdigit(), 'x'].astype(int)
Want to retrieve a slice from a string column in your #Python #Pandas data frame? Use .str.slice:
df['a'].str.slice(1, 10) # or .str[1:10]
df['a'].str.slice(1, 10, 2) # or .str[1:10:2]
df['a'].str.slice(None, 10) # or .str[:10]
df['a'].str.slice(1, None) # or .str[1:]
Want to retrieve from a string column in your #Python #Pandas data frame? Use .str.get:
df['a'].str.get(0) # one character
df['a'].str.get(i) # using an index variable
But wait: You can use [], in place of .get:
df['a'].str[0] # alt syntax!
A recent paper finds that when new albums drop, streaming traffic increases — and so do traffic fatalities. 🤯
In today's Bamboo Weekly, we investigate this data with #Python #Pandas, using a variety of data-analysis techniques — grouping, joins, and datetime values.
Check it out: buff.ly/ZtkMamY
Your #Python #Pandas data frame has a multi-index, and you want to remove one part — not return it to be a regular column? Add drop=True:
df.reset_index(level=1) # index level 1 becomes a column in df
df.reset_index(level=1, drop=True) # index level 1 is removed
Your #Python #Pandas data frame has a multi-index? Return selected parts to columns with the "level" keyword argument:
df.reset_index(level=1) # one column
df.reset_index(level=[0, 2]) # two columns
df.reset_index(level='y') # one column, if named
Yesterday's hands-on Claude+#Python workshop was great!
We built a shell utility, a FastAPI app, and a Discord bot. We discussed generating maintainable code, AI+human interactions, and subagents.
Join my Claude+#Pandas class on March 23 — or ask about doing this at your company: buff.ly/F8fwOC8
My daughter, who hates movies, has been waiting for this for a long time, since she read the book, and said that we'll go see it together. I already wanted to, but after seeing your post, we'll definitely go!
Return a #Python #Pandas data frame's index to a regular column with reset_index:
df = df.reset_index()
• 1-column index? It's now a regular column.
• Multi-index? Its columns are all regular columns.
reset_index returns a new data frame. It doesn't modify the original.
Turn a column in a #Python #Pandas data frame into an index with set_index:
df = df.set_index('x')
Remember, set_index returns a new data frame. It doesn't change the original one.
Turn multiple columns into a multi-index by passing a list:
df = df.set_index(['x', 'y'])
Fair enough, but there are times when it's not for printing, and your want a long, multiline string with dynamic content.
Want to include a dynamic value in a multi-line #Python string? That would require both an f-string and a triple-quoted string.
Good news: Python supports this!
x = 10
y = 20
s = f"""{x} + {y} = {x+y}
{x} * {y} = {x*y}"""
print(s) # shows 10+20 = 30 and also 10*20 = 200
Want to include a newline in a #Python string? Use \n:
s1 = 'abc\ndef' # 7 characters, including newline
That's fine for small strings. But for longer ones, use a triple-quoted string:
s2 = """abc
def"""
BTW, the created strings are the same:
print(s1 == s2) # True!
How many missile alerts does Israel receive each day? How long have they lasted? What hours are most common? And what cities have been alerted the most?
In the latest Bamboo Weekly, we explore all of this with #Python and #Pandas. Level up your data skills on current events: buff.ly/ZtkMamY
A classic #Python mistake: What's wrong with this code?
s = 'What's your name?'
The string uses '' as delimiters. But it also contains a ' inside. Solutions:
s = "What's your name?" # Delimit with ""
s = 'What\'s your name?' # Escape literal ' with \
With the US-Israel-Iran war in its second week, Iran continues to fire missiles at other countries, including Israel (where I live). How many missiles? And how long are we spending in our shelters?
Use #Python and #Pandas to answer these questions in the latest Bamboo Weekly: buff.ly/7xLd9J6
Want to read a non-text file with #Python? Specify "rb", for "read binary," to avoid errors.
t = open('myfile.zip').read() # error
t = open('myfile.zip', 'rb').read() # works!
What is t? A *byte* string, not a regular text string.
>>> type(t)
<class 'bytes'>
#Python tip: Don't write all 6 comparison methods!
Define __eq__ and __lt__, then add @total_ordering:
from functools import total_ordering
@total_ordering
class C:
def __lt__(self, o): ...
def __eq__(self, o): ...
You get >, >=, <= for free!
It's almost as if they have no idea what they're doing.
Trump will simply declare victory in the coming days. The Iranian government will then have even more motivation to pursue nukes, to prevent this kind of assault from happening in the future.
Curious about #Python and #Pandas with Claude Code?
Next week, I'm starting my second round of AI coding workshops, where we'll solve problems with Claude Code.
Watch yesterday's info session, where I explained my thinking, and my workshop plans: buff.ly/d3rZuGy
Questions? Ask me here!