-1

I have a list which looks like this :

[[[['one', 'two', 'three']]]]

How do I remove the outer brackets such that I get ["one", 'two', 'three']

These number of brackets can be arbitrary.

Humayun Ahmad Rajib
  • 1,488
  • 1
  • 9
  • 20

3 Answers3

1

You have a one-element, deeply nested list. You can use a loop to repeatedly replace the list with its first element. Stop when the first element is not a list.

lst = [[[['one', 'two', 'three']]]]
while isinstance(lst[0], list):
    lst = lst[0]
print(lst)
luther
  • 4,843
  • 1
  • 12
  • 22
0

You can search for a list that contains either multiple elements or a non-list element.

One possibility is recursion:

def strip_outer(x):
    if len(x) != 1 or not isinstance(x[0], list):
        return x
    return strip_outer(x[0])

I don't think you really need to create a new stack frame for this sort of iteration, so an iterative solution may be preferable:

def strip_outer(x):
    while len(x) == 1 and isinstance(x[0], list):
        x = x[0]
    return x
Mad Physicist
  • 95,415
  • 23
  • 151
  • 231
0

One way of removing the brackets of list [[[['one', 'two', 'three']]]] can be constantly checking the length of the list till it's no more 1, then finally replacing the original list.

def flatten(l):
    while len(l) == 1 and type(l[0]) == list:
        l = l.pop()
    return l

Using the function on the given list:

l = [[[['one', 'two', 'three']]]]

l = flatten(l)

print(l)
# Output
# ['one', 'two', 'three']

To make it work on a multi-dimensional list, we can use the above function to get our job done like this:

l = [
        [[['one', 'two', 'three']]],
        [['one', 'two', 'three']],
        ['one', 'two', 'three']
    ]

for i in range(len(l)):
    l[i] = flatten(l[i])

print(l)
# Output
# [
#   ['one', 'two', 'three'],
#   ['one', 'two', 'three'],
#   ['one', 'two', 'three']
# ]

Note: This approach will specifically work on multi-dimensional lists. Using this approach for a datatype other than list will result in an error.

Gagan Deep Singh
  • 322
  • 3
  • 11