I have a list like this:
my_lst = [[1,2,3,4]]
I was wondering how can I remove [] from the list to get the following list:
my_lst = [1,2,3,4]
I have a list like this:
my_lst = [[1,2,3,4]]
I was wondering how can I remove [] from the list to get the following list:
my_lst = [1,2,3,4]
The double [[]]
is because you have a list
containing a list
. To get out the inner list
, just index it:
my_lst = my_lst[0]
or unpack it:
[my_lst] = my_lst
Unpacking has the mild advantage that it will give you an error if the outer list
doesn't not contain exactly one value (while my_lst[0]
will silently discard any extra values).
my_lst = my_lst[0]
You have a list with one element, which is itself a list. You want the variable to just be that first element, the list 1,2,3,4.
You can use itertools
to achieve that without writing your explicit loop if the length of the outer list could be more than one.
In [47]: import itertools
In [49]: list(itertools.chain.from_iterable([[1, 2, 3], [1, 2]]))
Out[49]: [1, 2, 3, 1, 2]
You can reduce 1 dimension using sum
.
my_lst=sum(my_lst,[])
# [1,2,3,4]