Making a 2D list into a 1D list in python.
Asked
Active
Viewed 2,723 times
-1
-
1use 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 Answers
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
-
1You 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

Joab Leite
- 84
- 3