Pythonic way of copying an iterable object

折月煮酒 提交于 2019-12-04 07:12:55

Is there a best-practice in situations where one wants a copy of an iterable?

itertools.tee gives you two iterators that each yield the same items as the original, but it takes the original and memorizes everything it yields, so you can't use the original anymore. It wouldn't help here though, because it would keep on memorizing these cycled values until you get a MemoryError.

Or is copying iterables silly and useless in general?

iterators are just defined to have a current state and yield a item. You can't tell if they will yield the same items in the future or which items they yielded in the past. A real copy would have to do both, so it's impossible!

In your case it's so trivial to make a new cycle that I'd rather do that than try to copy an existing. For example:

def new_cycle( seq, last=None):
    if last is None:
        return cycle(seq)
    else:
        it = cycle(seq)
        while next(it) != last:
            pass
        return it
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!