Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python list and dictionary be nested infinitely?

Tags:

python

Recently I found that python list and dictionary can be nested in multiple level like this

a = {'a1':[{'a2':{'a3':[4,5,6]}}]}

So I'd like to ask is there a technical limit for the nested level? If there isn't, is there a conventional limit for nested level, what's it?

like image 833
Mario Avatar asked Jul 04 '26 11:07

Mario


1 Answers

The only limit is memory. Given infinite memory you can nest Python objects infinitely.

Demo:

>>> root = lst = []
>>> levels = 0
>>> while True:
...     lst.append([])
...     lst = lst[-1]
...     levels += 1
...     if levels % 1000000 == 0:  # every 1 million
...         print levels
... 
1000000
2000000
3000000
4000000
5000000
6000000
7000000
8000000
9000000
10000000
11000000
# ....
# [ slower and slower as the system starts to swap ]
# ....
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

For the sake of my sanity I killed it at 30 million objects though.

like image 62
Martijn Pieters Avatar answered Jul 06 '26 03:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!