If I make a deeply nested list, like this:
arr = [1]
for i in range(1000):
arr = [arr]
then
print(arr)
will work fine, but
str(arr)
fails miserably with maximum recursion depth exceeded. ("%s" % arr
, and repr(arr)
too.)
How could I get the string that print prints? And what is the underlying reason for the difference?
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
In this example, we will use list comprehension to Iterate the list first, and then we are iterating the sub-list using for loop. After that, we are appending the element in our new list “flatList” using a List Comprehension which gives us a flat list of 1 dimensional.
We can convert a nested list to a dictionary by using dictionary comprehension. It will iterate through the list. It will take the item at index 0 as key and index 1 as value.
You can increase the recursion limit. But this safeguard is there for a reason. Are you sure this is what you want to do?
import sys
sys.setrecursionlimit(2000)
arr = [1]
for i in range(1000):
arr = [arr]
str(arr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With