0

I have a Class (ElementList) that contains a lot of information. I have implemented a method (.ToArray()) that gets some information of the object and puts it in an array, or list.

I want to loop this array. When I do the following :

for Element in ElementList.ToArray()
    Do stuff

Does it execute .ToArray() every time?

Moose1231
  • 9
  • 4
  • Please provide the definition of `Element` and `ElementList`, and also of `ToArray` – Devesh Kumar Singh May 09 '19 at 15:37
  • 1
    no. It executes `ElementList.ToArray()` once, and assuming this returns an iterable, then executes the "Do stuff" code once for every element of that iterable – Robin Zigmond May 09 '19 at 15:37
  • Possible duplicate of [How does Python for loop work?](https://stackoverflow.com/questions/1292189/how-does-python-for-loop-work) – Sayse May 09 '19 at 15:37

1 Answers1

1

According to https://docs.python.org/3/reference/compound_stmts.html#the-for-statement,

for_stmt ::=  "for" target_list "in" expression_list ":" suite
          ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable object.

So your ElementList.ToArray() will be executed only once.

You can verify this experimentally by making your function print something; then you can observe that it only prints once.

>>> def make_list():
...     print("I'm being evaluated!")
...     return [1,2,3]
...
>>> for x in make_list():
...     print(x)
...
I'm being evaluated!
1
2
3
Kevin
  • 74,910
  • 12
  • 133
  • 166