Amon
Amon

Reputation: 2951

Exiting out of for loop and returning when at the end of a file

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

Answers (3)

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

You could use a list comprehension,

return [re.split('\s{2,}', line, 2)[1] for line in master_file]

Upvotes: 1

Savir
Savir

Reputation: 18418

Instead of return, use yield

It's like a return but it keeps the position in the iterable.

Upvotes: 3

Hyperboreus
Hyperboreus

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

Related Questions