Given a #Python list of numeric strings:

x = ['1', '2', '3']

I can try to use "sum(mylist)". But that'll fail, because they're strings. I can use a list comprehension to convert them:

sum([int(y)
for y in x])

But it also works without the []:

sum(int(y)
for y in x)

Huh?
List comprehensions return (by definition) lists. So this:

[int(y)
for y in x]

returns a list -- in this case, a list of ints. The list is returned all at once, though.
To save memory, it's often best to use a generator comprehension:

(int(y)
for y in x)

This doesn't return a list. Rather, it returns a generator, an object that knows how to behave in a "for" loop. You can say:

g = (int(y) for y in x)

for i in g:
print(i) # 1, 2, 3
I can use a generator where an iterable is wanted. For example, the builtin "sum" function:

sum((int(y)
for y in x))

Notice the double parentheses? Turns out you don't need them!

sum(int(y)
for y in x)

Python sees the generator expression, and does the right thing.

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Reuven M. Lerner, Python trainer

Reuven M. Lerner, Python trainer Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @reuvenmlerner

Jan 18
A #Python student showed me this code, and asked how to improve it:

def f(g, **kwargs):
for k, v in kwargs.items():
if "x1" == k:
g.x1 = v
elif "x2" == k:
g.x2 = v
elif "x3" == k:
g.x3 = v
First, what's this function doing?

- It gets an object and a dict of keyword arguments
- It goes through each keyword arg
- For three keys, it creates an attribute of that name on the object (g), with the value.

Let's assume the function can work for *all* keys. What can we do?
Well, we can always assign an attribute to nearly any Python object:

a.b = 100

This adds an attribute "b" to the object "a", with a value of 100 (an int).

We can accomplish the same with the "setattr" builtin:

setattr(a, 'b', 100)

Notice that 'b' is a string here!
Read 8 tweets
Jan 13
Many #Python beginners are confused by space characters, empty strings, and the term "whitespace." After all, how can nothing be something? (Or: How can something be nothing?)

A thread about nothing!

(Cue the Seinfeld theme, I guess...)
Given:

s = 'a b'

This string contains three characters. As humans, we only see the "a" and "b", two characters separated by a space.

But computers don't work that way: The space character is a character. It takes up just as much space in memory as either "a" or "b".
We can see this if we iterate over the characters in s, printing their Unicode numbers:

>>> s = 'a b'
>>> for c in s:
... print(ord(c))
...
97
32
98
Read 16 tweets
Dec 29, 2021
Want a #Python #pandas data frame with all Apollo missions, indexed by date?

df = pd.read_html('https://t.co/1OfUmAGe6N')[2]

df['Date'] = pd.to_datetime(df['Date'].str.replace('(–.+)?,', '', regex=True))

df = df.set_index('Date')
The first line scrapes the Wikipedia page for the Apollo program, putting all HTML tables into data frames. The missions are in the third table, aka index 2.

The second line turns lines containing date ranges into single (launch) dates, also removing commas and hyphens.
That second line then takes the resulting cleaned-up date strings, and passes them to pd.to_datetime. The resulting datetime series is then assigned back to df['Date'].
Read 4 tweets
Dec 5, 2021
For about a year now, I've been upset with the unvaccinated. Why don't they, or won't they, get vaccinated? Are they suicidal, ignorant, or sociopathic?

Two great books have changed my thinking: High Conflict, by @amandaripley, and Empire of Pain, by @praddenkeefe.

A thread.
First, just to make it clear: I'm vaccinated (3 shots). I think the covid vaccines are among the greatest achievements of modern science. My family all got vaccinated ASAP. They work, and save lives. Everyone should get vaccinated.
So my struggle hasn't been about the vaccines. Rather, it's how so many people have refused something so obviously beneficial, which will save not only their own lives, but the lives of people they love.

The evidence is overwhelming. So why the heck aren't they getting shots?
Read 25 tweets
Jun 4, 2021
Soon after you start to learn #Python, you start to hear that some data is mutable (i.e., can be changed), whereas other data is immutable (i.e., cannot be changed).

I find that many developers confuse "immutable" with "constant." These are very different ideas.
To appreciate the difference, remember that a Python variable is a reference to an object. It is *not* an alias for a location in memory.

So when you say "x = 5", you aren't sticking 5 in x's memory location. Rather, you are saying that the name "x" is another way to refer to 5.
In that sense, variables in Python are sort of like pronouns. You can refer to the object itself, or you can refer to it via its pronoun. However you refer to it, you get the same object.

When you assign a variable, you're saying that it (the pronoun) now refers to a new object.
Read 12 tweets
Jun 2, 2021
One of the hardest things for people to learn in #Python is list comprehensions. Some quick tips that make them easier to work with:

(1) Break them up into multiple lines! It drives me batty to see people writing comprehensions on a single line.
You can then reason about each line separately:

[int(x)
for x in '1 2 b 3'.split()
if x is.digit()]

Line 1: Expression
Line 2: Iteration
Line 3: Condition

Or if you're a fan of SQL:

Line 1: SELECT
Line 2: FROM
Line 3: WHERE
(2) The expression can be literally any Python expression. Any operator, function, or method. Including functions that you write.

(3) Don't use print as an expression. Comprehensions create lists. Print displays data on the screen. Also, print returns None — not what you want.
Read 12 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us on Twitter!

:(