Search code examples
pythonpython-3.xgenerator

how to loop through elements using generator and make transformation in python


I am trying to get a better understanding on how to use generator in python

Assuming that i have the function below:

names = ["john \t", " dave", "ana", " jenny"]


def function_for_generator(names):

    transformed_names = []

    for name in names:
        if name.endswith("\t"):
            cleaned_name = name.rstrip("\t").replace(" ", "")
            transformed_names.append(cleaned_name)
        elif name.startswith(" "):
            cleaned_name = name.lstrip()
            transformed_names.append(cleaned_name)
        else:
            transformed_names.append(name)
    return transformed_names
  

and the current result after calling this function: ['john', 'dave', 'ana', 'jenny']

I was able to rewrite something close to that using a while loop and an iterator but the solution i am looking for is to rewrite this function using a generator specifically?

If anyone could help me rewrite that function using a generator with a for loop or while loop, for my own understanding, thank you.


Solution

  • This is the code for the generator function you were expecting:

    names = ["john \t", " dave", "ana", " jenny"]
    
    def function_for_generator(names):
        for name in names:
            if name.endswith("\t"):
                cleaned_name = name.rstrip("\t").replace(" ", "")
                yield cleaned_name
            elif name.startswith(" "):
                cleaned_name = name.lstrip()
                yield cleaned_name
            else:
                yield name
    

    You can iterate over this generator function, like this:

    for x in function_for_generator(names):
        print(x)
    

    Or like this:

    transformed_names = [x for x in function_for_generator(names)]