0
array1=[1, 2, 3]
array2=[0, 1, 2]
a = [10, 20, 30]
b = [100, 200, 300]
padded = ['001', '002', '003']

array1 = iter(array1)
array2 = iter(array2)
a = iter(a)
b = iter(b)
padded = iter(padded)


func= (
    f"  array1 {next(array1)}  \n"
    f" array2 {next(array2)}  \n"
    f" ... a {next(a)}  \n"
    f" ... b {next(b)} \n"
    f" padded {next(padded)} \n"
)

for i in range(2):
    print(func)

Is not iterating.

Wasn't planning to be learning to code, though here we are. Really appreciate the help.

3
  • Is not iterating. is not a good way to tell your problem. Better would be to tell the intended output and the actual output along with errors(if any) Commented Apr 6, 2022 at 10:17
  • Why are you using iterators, you can you it in a simple loop ? Is that what you are looking for or you HAVE to use 'iter' and 'next' ? Commented Apr 6, 2022 at 10:18
  • @Grall I am too inept to answer this, but I need to 'generate' many unique copies of func.. I'd be interested to see the for loop method :~) Commented Apr 6, 2022 at 10:46

2 Answers 2

1

Note that I do not discuss you approach as such. I strictly address your question.


When you do

func = (
    f"  array1 {next(array1)}  \n"
    f" array2 {next(array2)}  \n"
    f" ... a {next(a)}  \n"
    f" ... b {next(b)} \n"
    f" padded {next(padded)} \n"
)

... you have defined func once for all. It is henceforth just a string... for ever...Incidentally, using func to name this string is somehow misleading.

If you want it to be redefined at each iteration, you have to call your nexts again and again... A possible approach* is to turn your variable func into a callable, say, using an anonymous function, as follows:

func = lambda: (
    f"  array1 {next(array1)}  \n"
    f" array2 {next(array2)}  \n"
    f" ... a {next(a)}  \n"
    f" ... b {next(b)} \n"
    f" padded {next(padded)} \n"
)

and then iteratively call it

for i in range(2):
    print(func())
Sign up to request clarification or add additional context in comments.

Comments

0

You can't iterate through an f string. Once the variable in the f string is defined it can't be changed after the next iteration. I would recommend using .format instead.

func= (
    "  array1 {}  \n".format(next(array1))
    f" array2 {}  \n".format(next(array2))
    f" ... a {}  \n".format(next(a))
    f" ... b {next(b)} \n".format(next(b))
    f" padded {next(padded)} \n".format(next(padded))
)

Also don't forget to index the arrays!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.