Tuesday Tip #33: Three useful Python tricks ๐Ÿ


Hi Reader,

Thanks for sticking with me through all of those Black Friday emails! ๐Ÿ˜‚

Seriously, though, I'm glad you're still here! ๐Ÿ™Œ

Now it's time to get back to the tips! ๐ŸŽ“


๐Ÿ”— Link of the week

โ€‹Visual Anagramsโ€‹

This is a collection of "multi-view" optical illusions generated by diffusion models (similar to DALL-E and Stable Diffusion). I can't get over how good these are, and I'd encourage you to spend a few minutes checking them out!

There's also a research paper explaining how these were constructed, as well as a Colab notebook you can use to create your own!


๐Ÿ‘‰ Tip #33: Learn 3 Python tricks in 3 minutes

On Friday, I was working on a problem from the Python Problem-Solving Bootcamp that I talked about last week.

The problem boils down to this:

You have a text file containing 2000 numbers (one per line). If you walk through them in order, how many times is the current number greater than the previous number?

For example, if the first 8 numbers looked like this...

118, 121, 123, 125, 134, 132, 137, 135

...the answer would be 5, since the value increases 5 times (and decreases 2 times) when walking through the numbers from left to right.

How would YOU solve this problem with code? Give it some thought, and then keep scrolling...


Read in the data

The first step is to read in the data. I used a context manager (the with block) to ensure that the file would automatically be closed.

Within the block, I used a list comprehension to read in the file line-by-line and convert each number (which was originally a string) into an integer:

We can slice the resulting list to view the first 8 elements, and also confirm the length of the list:

Now we're ready to solve the problem!


My solution

Here's the solution that I came up with:

How does this work?

  • I set count to zero, which tracks the number of times the value increases.
  • I set previous to be the first element in the nums list.
  • The for loop iterates through nums, starting with the second element since we don't need to compare the first element to itself.
  • During each iteration:
    • The count is incremented if the current number is greater than the previous number.
    • The current number becomes the previous number.

The resulting count is 1553, which turns out to be correct.

I think this is a reasonable and readable solution. However, the solution notebook (provided by the bootcamp) reminded me of three great Python tricks I could have used to write a more elegant solution!

I'll teach you those tricks below... ๐Ÿ‘‡


Python trick #1: Pair iterables with zip

This solution uses zip to avoid manually assigning current to previous at the end of each for loop iteration:

If you're not familiar with zip, it aggregates the elements from multiple iterables and returns an iterator of tuples.

In simpler language, zip pairs together elements from different objects so that you can work with them at the same time.

In this case, we're pairing together the nums list (starting with element 0) and the nums list (starting with element 1), and then unpacking each pair of elements into previous and current during each iteration of the for loop.


Python trick #2: Convert booleans to integers

This solution removes the conditional statement from the for loop:

How does this work?

  • The current > previous comparison returns a boolean value (either True or False)
  • When you try to do math with a boolean value, True gets converted to 1 and False gets converted to 0. Thus:
    • count += True evaluates to count += 1
    • count += False evaluates to count += 0.

Python trick #3: Use a generator expression

Finally, we can rewrite the solution even more concisely:

This converts the previous solution into a generator expression, which is like a list comprehension that is lazily evaluated.

Then, we pass the generator object to the sum function, which adds up all of the True values (by converting them to ones).


Want more Python practice?

My Python course includes 9 sets of exercises and a 7-part project. It's great for beginners and intermediate users alike.

Feel free to get in touch if you're wondering if it's right for you!


If you enjoyed this weekโ€™s tip, please forward it to a friend! Takes only a few seconds, and it really helps me reach more people! ๐Ÿ™

See you next Tuesday!

- Kevin

P.S. I'll give you 20 seconds to guess what this video is about (YouTube)

Did someone awesome forward you this email? Sign up here to receive Data Science tips every week!

Learn Artificial Intelligence from Data School ๐Ÿค–

Join 25,000+ intelligent readers and receive AI tips every Tuesday!

Read more from Learn Artificial Intelligence from Data School ๐Ÿค–

Hi Reader, Last week, I encouraged you to experiment with different LLMs, since thereโ€™s no one model that is superior across all use cases. Specifically, I suggested you try using Chatbot Arena, which allows you to chat with multiple models at once. Itโ€™s completely free, but has two significant disadvantages: Your chats are not private and may be used for research. It lacks the feature-rich interface provided by other LLMs. Today, I want to offer you a better method for experimenting with...

Hi Reader, Over the past 50 tips, Iโ€™ve touched on many different topics: Python, Jupyter, pandas, ML, data visualization, and so on. Going forward, Iโ€™m planning to focus mostly on Artificial Intelligence. Iโ€™m announcing this so you know what to expect, and I know what to deliver! ๐Ÿ’Œ Iโ€™ll also try to make the tips shorter, so that they're easier to digest on-the-go. Finally, I plan to include an โ€œaction itemโ€ each week, so that you can practice what youโ€™re learning. I hope you like these...

Hi Reader, Next week, Iโ€™ll be offering a Black Friday sale on ALL of my courses. Iโ€™ll send you the details this Thursday! ๐Ÿšจ ๐Ÿ‘‰ Tip #50: What is a "method" in Python? In Python, a method is a function that can be used on an object because of the object's type. For example, if you create a Python list, the "append" method can be used on that list. All lists have an "append" method simply because they are lists: If you create a Python string, the "upper" method can be used on that string simply...