Reputation: 2951
I want to loop through a file and return every line:
for i in master_file:
columns = re.split('\s{2,}', i)
last_name = columns[1]
print(last_name)
If I replace print
with return
it will only return columns[1]
for the first line, but I want to return it for all the lines. So I can use that info elsewhere in my function.
Upvotes: 2
Views: 59
Reputation: 56654
You could use a list comprehension,
return [re.split('\s{2,}', line, 2)[1] for line in master_file]
Upvotes: 1
Reputation: 18418
Instead of return
, use yield
It's like a return but it keeps the position in the iterable.
Upvotes: 3
Reputation: 32429
In this case you need to yield
the value and not return
it:
for i in master_file:
columns = re.split('\s{2,}', i)
last_name = columns[1]
yield last_name
Complete sample:
def readLastNames ():
for i in master_file:
columns = re.split('\s{2,}', i)
last_name = columns[1]
yield last_name
for last_name in readLastNames ():
print (last_name)
Very rough explanation: yield
passes the parameters and the control back to the calling context, perserves the state of the called context and resumes then from there.
Upvotes: 9