-1

Making a 2D list into a 1D list in python.

user13054857
  • 3
  • 1
  • 3
  • 1
    use sum( [[1,2,3,4,], [5,6,7]],[]) – Naga kiran Mar 13 '20 at 03:51
  • Does this answer your question? [How do I concatenate two lists in Python?](https://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python) – ilke444 Mar 13 '20 at 03:55
  • Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Errol Mar 13 '20 at 04:09
  • @Nagakiran, using `sum()` to flatten list of lists is like [Shlemiel the painter's algorithm](http://joelonsoftware.com/articles/fog0000000319.html) -- unnecessarily inefficient as well as unnecessarily ugly. It should never be used, imo. – Harshal Parekh Mar 13 '20 at 04:48

4 Answers4

3

This should work, give it a shot:

x = [[1,2,3,4,], [5,6,7]]
onlyList = []
for nums in x:
  for val in nums:
    onlyList.append(val)
print(onlyList)

Output:

[1, 2, 3, 4, 5, 6, 7]
de_classified
  • 1,927
  • 1
  • 15
  • 19
1

A one-liner with list comprehension. Basically this can be extended for any levels by adding an additional for term. Notice two for as its a 2d list.

two_dim = [[1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11]]
one_dim_list = [n for one_dim in two_dim for n in one_dim]

print(one_dim_list)
Abhilash
  • 2,026
  • 17
  • 21
0
first_list= [[1,2,3,4,], [5,6,7]]
final_list=first_list[0]+ first_list[1]
print(final_list) 
# [1, 2, 3, 4, 5, 6, 7]
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
  • 1
    You can either use the `code` block or Ctrl+K to format code in your answer. Also, this is not what the OP wants, it says only using `.append()`. – Harshal Parekh Mar 13 '20 at 04:56
-1

You can use cereja project

pip install cereja
import cereja as cj

cj.flatten([[1,2,3,4,], [5,6,7]])

Try youself:

https://colab.research.google.com/github/jlsneto/cereja/blob/master/docs/cereja_example.ipynb

See code: https://github.com/jlsneto/cereja/blob/66b7ef86a77140429f75e4dae3606c6abacac72f/cereja/arraytools.py#L244

Joab Leite
  • 84
  • 3