3

How would I get the elements iterated by a for loop to a list where I can print them out later in the my code? For example:

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

fname only shows all the elements from dirlist only in the loop. I would like to view the elements at other areas in my code. I tried li = fname ... but only one element shows up, when in fact there are about 7 elements. Thanks!

suffa
  • 3,606
  • 8
  • 46
  • 66

1 Answers1

6

You can use a list comprehension:

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

to print the filenames, use

print "\n".join(tarfiles)

or

for fname in tarfiles:
    print fname
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841