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.
(4) The source in line 2 can be a list, but also a tuple, dict, set, file, or anything else.

(5) Comprehensions don't modify the data on which they run. They create new data structures.
(6) There are several kinds of comprehensions:

- List comprehensions create a new list
- Dict comprehensions create a new dict
- Set comprehensions create a new set

There are also generator expressions, which return a generator object.
(7) The "for" loop (line 2) runs first, then the "if" condition. If the condition returns True, then the expression (line 1) runs, and its value is placed into the output list.

(8) The condition can be as simple or as complex as you want.
(9) You can have more than one "if" condition! Those are joined (anded, if you will) together. So you can say

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

This isn't needed for simple joined conditions, but can make things much easier to read.
(10) Nested comprehensions are really hard to read and understand... until/unless you do them on multiple lines. They are written as:

[expression
for #1
optional if #1
for #2
optional if #2
etc.]

Consider:

mylist = [[10, 20, 30], [40, 50], [60, 70, 85]]
We can say:

[x
for sublist in mylist
for x in sublist]

We get:

[10, 20, 30, 40, 50, 60, 70, 85]

But what about:

[x
for sublist in mylist
for x in sublist
if x % 2]

Now we get:

[85]

Since only one number is odd.
We can also say:

[x
for sublist in mylist
if len(sublist) < 3
for x in sublist
if not x % 2]

and we get:

[40, 50]

All even numbers in the only sublist with fewer than 3 elements.
Once you internalize how to write comprehensions, they become natural to write (and even read). Until that, it's natural to say, "Who needs this?" But make an effort to try them, and it will pay off!
BTW, I love comprehensions so much, I have a course about them: store.lerner.co.il/comprehending-…

And comprehensions are an important part of my corporate training... so if your company needs help understanding them (or anything else in Python), let me know!

• • •

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

Keep Current with Reuven M. Lerner

Reuven M. Lerner 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

4 Jun
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
15 Oct 20
Some thoughts on teaching online (a thread).

Background: I've done corporate #Python and data-science training for 20 years. Even before the pandemic, I taught live, online courses (via WebEx and Zoom) at least 1 week/month. I also offer many video (recorded) courses.
My work slowed down in April-May, when companies didn't know what was happening.

Training is now about where it was before. Except it's 100% online.

I teach everything from "Python for non-programmers" to "intro to data science." 5 days/week, 4-8 hours/day. All online.
I've learned a lot in this time, and want to share these thoughts with others — learners (no pun intended), teachers, and training managers.

Also: I teach adults at companies. I have huge respect and sympathy for schoolteachers who have been thrust into this world.
Read 20 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 Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(