Home Backend Development Python Tutorial Discovering itertools

Discovering itertools

Sep 03, 2024 am 10:40 AM

Descubriendo itertools

Itertools is one of the most interesting python libraries. It contains a series of functions inspired by functional languages ​​that are used to work with iterators.

In this article I will mention some of the ones that have caught my attention the most and that are worth keeping in mind so as not to reinvent the wheel every time.

Count

Several times I have implemented an infinite count (well, it ends
explicitly at some point with a break) using a while True loop. itertools offers us a better alternative:

    from itertools import count

    for i in count(start=2, step=2):
        if i > 10:
            break
        print(i)

Copy after login
    2
    4
    6
    8
    10
Copy after login
Copy after login

As can be seen in the example, if it were not for the break, count would return infinite numbers. The above code is roughly equivalent to:

    i = 2

    while True:
        if i > 10:
            break

        print(i)
        i += 2

Copy after login
    2
    4
    6
    8
    10
Copy after login
Copy after login

batched

A function to do something very common: get data from a sequence in batches of size n. Let's look at an example:

from itertools import batched

    sequence = [1, 2, 3, 4, 5, 6, 7]

    for batch in batched(sequence, 2):  # lotes de tamaño 2
        print(batch)
Copy after login
    (1, 2)
    (3, 4)
    (5, 6)
    (7,)
Copy after login

It should be noted that the last batch may be of a size less than or equal to n, as in this case. Quite useful, don't you think?

pairwise

Another simple and useful function. Given a sequence (actually, given an iterator), it gives us its elements in pairs.

Let's see it better with an example:

from itertools import pairwise

    sequence = [1, 2, 3, 4, 5, 6, 7]

    for a, b in pairwise(sequence):
        print(a, b)
Copy after login
    1 2
    2 3
    3 4
    4 5
    5 6
    6 7
Copy after login

The number of pairs is one less than the size of the input sequence.

product

Finally, for this short entry, I want to talk about product, a
implementation of the Cartesian product.

Useful to replace a nested for that loops through two data streams:

from itertools import product

    A = [1, 2, 3]
    B = [5, 6, 7]

    for a, b in product(A, B):
        print(a, b)
Copy after login
   1 5
    1 6
    1 7
    2 5
    2 6
    2 7
    3 5
    3 6
    3 7
Copy after login

Receives a parameter that allows us to make the Cartesian product of a
sequence with itself:

   from itertools import product

    A = [1, 2, 3]

    for a1, a2, a3 in product(A, repeat=3):
        print(a1, a2, a3)
Copy after login
    1 1 1
    1 1 2
    1 1 3
    1 2 1
    1 2 2
    1 2 3
    1 3 1
    1 3 2
    1 3 3
    2 1 1
    2 1 2
    2 1 3
    2 2 1
    2 2 2
    2 2 3
    2 3 1
    2 3 2
    2 3 3
    3 1 1
    3 1 2
    3 1 3
    3 2 1
    3 2 2
    3 2 3
    3 3 1
    3 3 2
    3 3 3
Copy after login

In a future post, I will mention other functions of this useful
module python standard library. I hope it is useful to you.

The above is the detailed content of Discovering itertools. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles