[Python-ideas] More classical for-loop

Steven D'Aprano steve at pearwood.info
Sat Feb 18 02:05:10 EST 2017


On Sat, Feb 18, 2017 at 03:27:00AM +0100, Mikhail V wrote:

> In what sense iteration over integer is limited?

It cannot iterate over something where the length is unknown in
advance, or infinite, or not meaningfully indexed by integers.


Here are four for-loops. How would you re-write this using indexing? 
Don't forget the list comprehension!


for directory, subdirs, files in os.walk(top):
    files.sort()
    for f in files:
        print(os.path.join(top, directory, f))
    # skip .git and .hg directories, and those ending with ~
    for d in ('.git', '.hg'):
        try: subdirs.remove(d)
        except ValueError: pass
    subdirs[:] = [d for d in subdirs if not d.endswith('~')]
    subdirs.sort()


-- 
Steve


More information about the Python-ideas mailing list