Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning elements from a for loop to another list [duplicate]

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!

like image 251
suffa Avatar asked Apr 19 '26 02:04

suffa


1 Answers

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
like image 154
Sven Marnach Avatar answered Apr 20 '26 14:04

Sven Marnach