-1

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]
pm980
  • 123
  • 11
Spedo
  • 355
  • 3
  • 13
  • 1
    @Sociopath: It might be inside a `dict`, and it's technically a legal type annotation in modern Python, but yes, on its own, it's unlikely to be what anyone actually wants. – ShadowRanger Mar 12 '20 at 17:32

5 Answers5

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

There are many other options.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
2

you have a list of lists.

my_lst = my_lst[0] #get the first list of the list
Peter
  • 169
  • 5
2
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.

katardin
  • 596
  • 3
  • 14
1

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]
dhu
  • 718
  • 6
  • 19
-1

You can reduce 1 dimension using sum.

my_lst=sum(my_lst,[])
# [1,2,3,4]
  • This is a really terrible general approach. It happens to be fine (if somewhat weird) for the single inner `list` case, but it's a [Schlemiel the Painter's algorithm](https://en.wikipedia.org/wiki/Schlemiel_the_Painter's_algorithm) when it comes to generalized flattening of an iterable of `list`s, with quadratic runtime (where `list`ifying the iterator produced by `itertools.chain`/`itertools.chain.from_iterable` is the correct solution for that case, having linear runtime). – ShadowRanger Mar 12 '20 at 17:37