0

I have a list in Python.

I have tried to set print(*arr, sep=",") refer "Print list without brackets in a single row". But my real problem is:

### List
num = 2
arr= [0, "txt", 4, 5, [3,4, num]]
# print full
print(arr)

# print an arr without brackets
print(*arr, sep=",")
  • Expected result: 0,txt,4,5,3, 4, 2

  • Actual result: 0,txt,4,5,[3, 4, 2]

The compiler does not remove brackets from sub-list. Please give me advice to fix it. Thanks!

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

0

Use a function to flatten the list first, and then print the new list.

def flatten(original, iterables=[list]):
    out = []
    for val in original:
        if type(val) not in iterables:
            out.append(val)
        else:
            out += flatten(val)
    return out


print(flatten(arr))

Here I explicitly specify type(val) != list so that it will not attempt to split up your strings, but will flatten sub lists. Additionally, this method will handle nested lists of any depth.

Result:

>>> print(flatten(arr))
[0, 'txt', 4, 5, 3, 4, 2]

You can also pass a second argument iterables, which is a list containing what iterable types you wish to flatten. This can include list, tuple, or anything else. Here I default to list since that's what your example requires.

Dillon Davis
  • 6,679
  • 2
  • 15
  • 37
0

try this for removing nested bracket only from the list:

num = 2    
arr = [0, "txt", 4, 5, [3,4, num]]    
output = []     
def removeBracket(arr): 
    for i in arr: 
        if type(i) == list: 
            removeBracket(i) 
        else: 
            output.append(i)   
removeBracket(arr)
print(output) # [0, 'txt', 4, 5, 3, 4, 2]
Dev.rb
  • 487
  • 6
  • 14