Home > Software design >  how to loop through elements using generator and make transformation in python
how to loop through elements using generator and make transformation in python

Time:04-25

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.

CodePudding user response:

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)]

CodePudding user response:

Given the specific values in your question then:

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

def function_for_generator(names):
  for name in names:
    yield name.strip()

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

Or, if you just want a new list then:

newlist = list(function_for_generator(names))

This works because strip() removes both leading and trailing whitespace

  • Related