0

If I have a generator that sequentially returns items in a list, is there any way to make the first return something different? e.g. if the list is ['apple', 'bag', 'cat', 'dog'...], could I make the generator yield

'apple is the first item'
'bag'
'cat'
'dog'

etc?

For some context: I am trying to stream a large file through flask using a generator object.

davidism
  • 121,510
  • 29
  • 395
  • 339
Alex Gao
  • 11
  • 3

2 Answers2

0

You can consume the first element, modify it and yield it; then yield the rest.

def mark_first_item(it):
    first = next(it)
    yield f"{first} is the first item"
    yield from it

stuff = ['apple', 'bag', 'cat', 'dog']
print(list(mark_first_item(iter(stuff))))
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

You can try enumerate

items = ['apple', 'bag', 'cat', 'dog']
genItems = (f"{v} is first element" if i==0 else v for i, v in enumerate(items))
Hemant
  • 1,127
  • 1
  • 10
  • 18