2

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.

Amon
  • 2,725
  • 5
  • 30
  • 52

3 Answers3

9

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.

Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • I've tried using yield before, I keep getting this error: `` – Amon Apr 05 '14 at 22:28
  • @Amon This is not an error. It is a generator. You need to consume it. Something like the last two lines of my second snippet. `for x in myGeneratorFunction(): print(x)`. – Hyperboreus Apr 05 '14 at 22:29
  • Oh my bad, it worked indeed. Can I use this method to create variables (like `last_name`) that I can use inside the function? – Amon Apr 05 '14 at 22:38
  • What name (variable) to assign to each yielded value is your choice. – Hyperboreus Apr 05 '14 at 22:54
  • So I have to use something like those last two lines right? What I want is to have different variables represent columns[1], columns[2] etc.. Then do something else with that variable, rather than just print it out – Amon Apr 05 '14 at 23:31
  • @Amon Process it as normal: `for x in generator(): doWhatEverYouWantWith (x)` – Hyperboreus Apr 06 '14 at 01:52
3

Instead of return, use yield

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

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
1

You could use a list comprehension,

return [re.split('\s{2,}', line, 2)[1] for line in master_file]
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99