Jack Ryandal
Jack Ryandal

Reputation: 9

python for loops: What does this does?

I am new to python, i was working with python random module and for loops.

accidentally I typed this

from random import choice

secret_num = []
for i in range(4):
    num = choice(range(10))
    secret_num.append(secret_num)

print(secret_num)

instead of appending num to secret_num list i appended secret_num

but now i am curious what this program does.

I got this output:

[[...], [...], [...], [...]]

Upvotes: 0

Views: 54

Answers (1)

Akshay Sehgal
Akshay Sehgal

Reputation: 19322

secret_num = [] is an empty list that you are appending to itself (which technically turns it into a non-empty one). This is called self-referencing.

What is happening is that secret_num is storing itself as an object, but, since the size of secret_num is dynamic (as you add items to the meta-list, the sublists also increase in size), the lists are shown with ... or the Ellipsis.

Note: It's not possible to print an object which has been modified with the insertion of itself, as it would enter infinite recursion. Think about it, if you modify the list by inserting itself into it, the new updated list that you are referring to would be inserted into itself as well, since you are only pointing to the object. This is why python uses the ellipsis (...) instead of the actual objects.

Read this previous answer of mine, which talks about this in more detail.

Upvotes: 2

Related Questions