开发者

Python Iterators: What does iglob()'s Iterator provide over glob()'s list?

开发者 https://www.devze.com 2023-01-27 06:58 出处:网络
Given the piece of code: from glob import glob, iglob for fn in glob(\'/*\'): print fn print \'\' for fn in iglob(\'/*\'):

Given the piece of code:

from glob import glob, iglob

for fn in glob('/*'):
    print fn

print ''

for fn in iglob('/*'):
    print fn

Reading the documentation for glob I see that glob() returns a basic list of files and iglob an Iterator. However I'm able to iterate over both and the same list of files is returned by each of them.

I've read the documentation on Iterator but it hasn't shed anymore light on the subject really!

So what benefit does iglob() returning an Iterator provide me over the list from glob()? Do I gain extra functionality over my old friend the lowly l开发者_如何学编程ist?


The difference is mentioned in the documentation itself:

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

Basically list will have all the items in memory. Iterator need not, and hence it requires less memory.


Adding to amit's answer. iglob() is useful in the particular case where if you delete a directory in the list, the files and folders in the list will be stored by glob() and hence further access in the loop throws exception. But by using iglob() we can overcome the concurrent modification exception

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号