0

Does this code create an infinitely deep list?

foo = ['Hello']
bar = [foo]*100
foo[0] = bar
print foo
print foo[0] == foo
print foo == bar

Because that is what it seems like, but how is it not taking up infinite amounts of memory then, everything is still running smoothly. Does it take up less memory because of pointers? Also, if I were to get to the bottom what value would I find? Where has the original 'Hello' gone in the computer's memory?

Note:
this is not a duplicate, because of the last question.

tox123
  • 318
  • 9
  • 21

1 Answers1

4

No, it creates two lists: one with a single item, and one with 100 items that all point to the first list. It then makes the single item in the first list point to the second list.

So it does not make an infinitely deep list; it just creates a cycle. If you created a loop that tried to continuously read the first element of the current item and then recurse, it would run infinitely (or at least, it would run until it hit Python's recursion limit), but that's because it's just going in circles.

Just like a circle doesn't have an infinite circumference - it has a finite circumference, but that doesn't mean you can't keep going around in circles forever.

Amber
  • 507,862
  • 82
  • 626
  • 550