Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a deeply nested list to a string

Tags:

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?

like image 333
vagoston Avatar asked Feb 12 '18 13:02

vagoston


People also ask

How do I turn a list into a string?

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.

How do I convert a nested list to a flat list?

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.

How do I convert a nested list to a dictionary?

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.


1 Answers

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)
like image 118
jpp Avatar answered Oct 11 '22 15:10

jpp