Home > Enterprise >  Operate a variable from 'any' iterator
Operate a variable from 'any' iterator

Time:01-17

I'm trying to make a bit more readable logging messages for my program.
For this purpose I'm searching a way to implement sort of advanced 'any' iterator.

It should either way return index of satisfying data index or iterated cell itself instead of just returning True/False on satisfied condition.

Here is a possible pseudo-code for explanation:

messages = [(0, None),(1, None), (2, "data")]

if any(data is not None for id, data in messages):
    print(f"Tuple with data has id: {id} and data: '{data}'.") 
else:
    print(f"There is no message with filled data")

# should output: "Tuple with data has id: 2 and data: 'data'."

I've tried several ways like using walrus operator, using global operator, print inside if operator or even implementing my own iterator
(but this topic is new for me so probably it still can be a solution)

I would like to avoid any extra for cycle for better optimization, readability and also for mastering python.

Thank you for any ideas in advance!

CodePudding user response:

Use a for loop and break out when the matching element is found. If you don't break out, print the message saying nothing was found.

for id, data in messages:
    if data is not None:
        print(f"Tuple with data has id: {id} and data: '{data}'.")
        break
else:
    print(f"There is no message with filled data")

CodePudding user response:

If you really want something similar to what you've already written, you can use next() on a filtering generator expression and catch StopIteration. But personally, I think it's clearer to use a plain for-loop like Barmar suggested.

try:
    id_, data = next((id_, data) for id_, data in messages if data is not None)
except StopIteration:
    print("There is no message with filled data")
else:
    print(f"Tuple with data has id: {id_} and data: '{data}'.")

(Here I'm also avoiding shadowing the builtin id function.)

  • Related