2

This is a noob question. Lets say I have alist like this:

a=[[1,2,3],[4,5,6]]

How do I remove all brackets. I know how to use join() function to remove 1st level of brackets. But can't seem to remove all.

  • 3
    What do you mean by remove all the brackets? Are you just trying to make a string like `"1,2,3,4,5,6"`? You couldn't use `str.join` alone to even remove one level of brackets in a case like `[1,2,3,4,5,6]` (because the contents aren't strings), so it's not clear what you mean by "remove brackets" in the first place. – ShadowRanger Dec 04 '21 at 02:53
  • How to flatten lists of lists: https://stackabuse.com/python-how-to-flatten-list-of-lists/ – Alex Reynolds Dec 04 '21 at 02:55
  • 1
    I agree with ShadowRanger: it's not clear what you're trying to do. Please [edit] to clarify. BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Dec 04 '21 at 03:13

3 Answers3

3

One thing you can easily do is to use itertools.chain:

import itertools

a=[[1,2,3],[4,5,6]]

print(*itertools.chain.from_iterable(a), sep=', ') # 1, 2, 3, 4, 5, 6

It assumes the depth of nesting is two.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • This is probably the fastest option. Look here (https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – carlosdafield Dec 04 '21 at 03:02
1

If you wish to end up with a string like "1,2,3,4,5,6" then you need to join each constituent list, then join those results.

",".join(",".join(lst) for lst in a)
Chris
  • 26,361
  • 5
  • 21
  • 42
1

This is a recursive function you can make to flatten a list.

It will work for your list a=[[1,2,3],[4,5,6]] and even weirder list like a=[[1,[2,3]],[4,[5],[6]]]

def flattenLst(lst):
    newLst = []
    _flattenLstHelper(lst,newLst)
    return newLst
    
def _flattenLstHelper(val,newLst):
    if not isinstance(val, list): # If it's not a list add to new list
        newLst.append(val)
        return
    for elem in val: # if it's a list recursively call each element
        _flattenLstHelper(elem,newLst)
        
print(flattenLst(a))    
carlosdafield
  • 1,479
  • 5
  • 16