Search code examples
pythonlist-comprehensionpython-itertools

How to remove a tuple in an integer tuple, if its last element is "0", using Python itertools?


I have the following code to create a tuple contains multiple tuples with integer pairs:

iterable = (
    tuple(zip([0, 1, 2], _))
    for _ in product(range(9), repeat=3)
)
next(iterable)  # First element is not needed
print(list(iterable))

# This code produces: [((0, 0), (1, 0), (2, 1)), ... , ((0, 8), (1, 8), (2, 8))]

But I need that if last element of a tuple is "0" (e.g. (0, 0) or (2, 0)), I have to remove that tuple. So new list should be like this:

[((2, 1),), ... , ((1, 2), (2, 7)), ((1, 2), (2, 8)), ... , ((0, 8), (1, 8), (2, 8))]

I actually achieved this goal by the following code but it is not the correct way I think, I don't know:

x = ()
for i in iterable:
    y = ()
    for j in i:
        if j[-1] != 0:
            y += (j,)
    x += (y,)
print(list(x))

How can I do this with itertools module and in one line, if possible? If needed, I can change the code at the top of this question, to create the desired list in one line.

Thank you.


Solution

  • Use filter() to remove the elements ending in 0 from the result of zip().

    iterable = (
        tuple(filter(lambda x: x[-1] != 0, zip([0, 1, 2], _)))
        for _ in product(range(9), repeat=3)
    )