Criando helpers cíclicos – Python

Criando <i>helpers</i> cíclicos – Python

Adapatado do Original: Tray Hunner – Python Morsels


 

Python tip: create looping helpers

Python’s for loops are all about looping over an iterable. That is their sole purpose.

Since Python’s for loops are more special-purposed than some programming languages, we need to embrace loopers to make our lives easier.

Python’s built-in looping helpers are enumeratezip, and reversed. You could also think of sorted as a looping helper. Any function that accepts an iterable and returns a new iterable could be thought of as a looping helper.

I think you should invent your own looping helpers.

By that I mean that you should look for patterns in your code’s looping logic that could be bundled up into a helper function, preferably a generator function.

Here are some examples.

Value with index


The enumerate function returns a 2-item tuple of a number and an item. But what if you find yourself swapping the 2-item tuple values over and over throughout your code:

>>> indexes = {value: index for (index, value) in enumerate(iterable)}

If there was a looping helper that did the same thing as enumerate but the order of the tuple items were reversed, then we could do this:

>>> indexes = dict(with_indexes(iterable))

Let’s make that looping helper:

def with_indexes(iterable):
    for i, item in enumerate(iterable):
        yield (item, i)


Check out the result of using with_indexes:

>>> colors = [“purple”, “blue”, “green”]
>>> indexes = dict(with_indexes(colors))
>>> indexes
{‘purple’: 0, ‘blue’: 1, ‘green’: 2}


We’ve made a generator function that uses enumerate, but the resulting generator values have the 2 items in the tuple swapped.

Counting downward


Python’s built-in enumerate function is great for counting upward while looping… but what if you need to count downward?

You could simply negate each number that enumerate gives you… but if you find yourself doing this multiple times in your code, I’d consider making your own custom looping helper. We could call it denumerate:

def denumerate(iterable, start=0):
    for n, value in enumerate(iterable, start=-start):
        yield (-n, value)

The negating of start and negating of the n number is an interesting way to count “downward” while actually counting upward.

Try that generator function out yourself:

>>> for n, color in denumerate(colors, start=len(colors)):
…     print(n, color)

3 purple
2 blue
1 green
 

Existing looping helpers


Before you write your own looping helper, do a quick search to see if there’s already one in the itertools module (or even a third-party module) that you could use.

For example, while creating a fun bit of scroll art which was inspired by Al Sweigart’s scrollart.org, I found I needed a looping helper. I checked the itertools module (a great first place to look for these helpers) and found that cycle was just what I needed.
 

But how…?


Not sure what that yield statement does or how to even get started making your own looping helpers?

See this week’s sneak peeks below. 👇
 

Sneak peek of the week: making looping helpers

This week’s sneak peek is two-fold:
 
  1. Videos and articles to help you create looping helpers
  2. Hands-on practice writing your own looping helpers

First, on creating your own looping helpers:
 
If you feel like you need a bit more easing into this topic than those first couple videos, watch my Lazy Looping: The Next Iteration talk.

After you’ve watched videos, what’s the next step?

Remember what I said about learning a couple weeks ago:
 
“You don’t learn by putting information into your head. You learn by trying to retrieve information from your head.”
 
Here are a few looping helpers to get you started.
 
  • uniques_only: get unique iterable items while maintaining item order
  • with_previous: get each iterable item along with the previous item
  • chunked: break an iterable into N-length chunk
  • interleave: interleave items from each of the given iterables
  • window: get each iterable item and the next N-1 items

All of those exercises would be great ways to practice creating your own custom looping helpers in Python. Sign up for a free Python Morsels account to try 3 of those exercises for free.

New this week: pointers, triangles, Python intro

Last Thursday I published an updated video of one of the first Python screencasts I published on Python Morsels: variables are pointers.

I made a fun scrolling Sierpiński triangle script on Thursday too, inspired by a Mastodon post.

If you trust my server and that script, you can run one of these commands to download and immediately run that fun visual from your system terminal…

On Linux:

curl -L pym.dev/p/3cmma | python3

On Windows (I think this works?):

(Invoke-WebRequest -Uri https://www.pythonmorsels.com/p/3cmma/).Content | python3

I also published an article on Friday about how to install a custom build of Python using pyenv. That’s a fairly niche topic, but I figured out how to do it on Friday for the sake of testing out a new Python REPL that will land in Python 3.13 (for Linux and Mac users only sadly) and I figured the discovery process I spent might help someone else.

Lastly, over the last few weeks I’ve been hard at work on Python exercises targeted at brand new programmers. If you signed up for Python Morsels, tried it out, and thought “I don’t think I’m ready for this”, click this link and I’ll immediately add you to a wait list to be notified about an eventual Intro to Python course.
P.S. Have a Python tip you think I should share? I’d love to hear it! Don’t worry whether I’ve shared something similar recently. Hit reply and write a couple sentence summary of your tip! 💌
"The exercises are wonderful, but your explanations are also pure gold: tremendously effective. The cost-benefit ratio of watching/reading them tends to zero." - Nacho Núñez, Python Morsels user

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*