-2

I have a very simple example of for loop in Python:

for el in [1, 2, 3, 4]:
    print(el)

I know that in for loop interpretator calls __iter__ from list to get list iterator.

I have some questions:

  1. Are all elements of this list stored in memory before the beginning for loop?
  2. Please explain how the for loop works in this case. What is the deep mechanism of for loop?
blackbrandt
  • 2,010
  • 1
  • 15
  • 32
  • 3
    Yes, as soon as you created a list literal, all of the elements of the list are stored in memory. – Chris Jul 15 '23 at 20:30
  • 2
    Does this answer your question? [Do Python's iterables really store all values in memory?](https://stackoverflow.com/questions/36619152/do-pythons-iterables-really-store-all-values-in-memory) – Zero Jul 15 '23 at 20:36
  • You might be interested in the `dis` package as well as these answers – JonSG Jul 15 '23 at 20:59

2 Answers2

0

let's imagine Python as a friend reading a list [1, 2, 3, 4] aloud. It starts from the beginning and reads each number, one by one. Every time it reads a number, it "prints" it out

About your memory question: Yes, the list [1, 2, 3, 4] is stored in memory. It's like having the whole list written down on a piece of paper before your friend starts reading.

algorythms
  • 1,547
  • 1
  • 15
  • 28
0

The semantics of a for loop can be expressed using a while loop and explicit calls to next.

Your loop

for el in [1,2,3,4]:
    print(el)

could be written as

itr = iter([1,2,3,4])
while True:
    try:
        el = next(itr)
    except StopIteration:
        break
    print(el)
del itr

itr is a value of type list_iterator which wraps an otherwise anonymous list [1,2,3,4]. Each value of the list is in memory, but you can only access them via itr by calling next (or calling itr.__next__ explicitly).

A list provides random access to its elements via list.__getitem__. A list_iterator does not. As far as I know, there is no way to access the underlying list of a list_iterator; you can only use __next__ to access the element an internal reference points to.

chepner
  • 497,756
  • 71
  • 530
  • 681