Assigning items from a for loop to another list

How do I get elements that repeat in a for loop to a list where I can print them later in my code? For instance:

 for fname in dirlist:
    if fname.endswith(('.tgz','.tar')):
       print fname

fname displays only all elements from dirlist only in a loop. I would like to view items in other areas of my code. I tried li = fname ... but there was only one element when there really are about 7 elements. Thank!

+3
source share
1 answer

You can use list comprehension:

tarfiles = [fname for fname in dirlist if fname.endswith(('.tgz','.tar'))]

to print file names use

print "\n".join(tarfiles)

or

for fname in tarfiles:
    print fname
+6
source

All Articles