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.
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.
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.
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)
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))