5

I'm super amazed using the generator instead of list. But I can't find any solution for this question.

What is the efficient way to get the first and last element from generator items? Because with list we can just do lst[0] and lst[-1]

Thanks for the help. I can't provide any codes since it's clearly that's just what I want to know :)

mark12345
  • 233
  • 1
  • 4
  • 10

1 Answers1

8

You have to iterate through the whole thing. Say you have this generator:

def foo():
    yield 0
    yield 1
    yield 2
    yield 3

The easiest way to get the first and last value would be to convert the generator into a list. Then access the values using list lookups.

data = list(foo())
print(data[0], data[-1])

If you want to avoid creating a container, you could use a for-loop to exhaust the generator.

gen = foo()
first = last = next(gen)
for last in gen: pass

print(first, last)

Note: You'll want to special case this when there are no values produced by the generator.

flakes
  • 21,558
  • 8
  • 41
  • 88
  • 2
    This is great. since I don't want to convert them to list, The first=last=next(gen) is what I'm looking for. I tried and it worked. Thank you very much – mark12345 Jul 17 '21 at 17:13