Reputation: 899
Python list in for loop, how do I have all in one list
import os
dir="/tmp/logvol/logs/fil/sap/archive/"
n=os.listdir(dir)
#print n
for x in n:
#print x
l = [];
l.append(os.path.join(dir,x))
print l
output:
['/tmp/logvol/logs/fil/sap/archive/m.log']
['/tmp/logvol/logs/fil/sap/archive/k.log']
['/tmp/logvol/logs/fil/sap/archive/j.log']
['/tmp/logvol/logs/fil/sap/archive/p.log']
Instead of multiple lists, I need all in one list.
['/tmp/logvol/logs/fil/sap/archive/m.log', '/tmp/logvol/logs/fil/sap/archive/k.log', '/tmp/logvol/logs/fil/sap/archive/j.log', '/tmp/logvol/logs/fil/sap/archive/p.log']
Upvotes: 2
Views: 167
Reputation: 4182
You recreate l
list every iteration of for
loop
for x in n:
#print x
l = []; # here You recreate list every iteration
l.append(os.path.join(dir,x))
print l
to avoid this instantiate list before for
loop
l = []; # here You recreate list every iteration
for x in n:
l.append(os.path.join(dir,x))
print l
and pick other name for variable, not l
because http://www.python.org/dev/peps/pep-0008/#names-to-avoid
Upvotes: 0
Reputation: 7210
Another way of doing it is with list comprehension.
l = [os.path.join(dir,x) for x in n]
Upvotes: 9
Reputation: 22912
You need to move your declaration of the list l
outside the loop:
l = []
for x in n:
#print x
l.append(os.path.join(dir,x))
Also, you don't need semicolons in Python.
Upvotes: 5