0

I'm trying to simplify two neested for loops in python but I cant resolve this. My code:

head = [[1, 2], [3, 4]]
temp = []
for array in head:
    for element in array:
        temp.append(element)
print(temp)
========OUTPUT========
[1, 2, 3, 4]

I try:

head = [[1, 2], [3, 4]]
temp = []
for array in head:
   temp += [element for element in array]
print(temp)

But only can simplify one loop

EDIT: SOLUTION

Specific solution for my case by @serafeim:

head = [[1, 2], [3, 4]]
print([element for array in head for element in array])

Other solutions:

By anon

from functools import reduce
head = [[1, 2], [3, 4]]
print(reduce(list.__add__, head))

By: @chepner

from itertools import chain
head = [[1, 2], [3, 4]]
print([x for x in chain.from_iterable(head)])

By: @R-zu

import numpy as np
head = [[1, 2], [3, 4]]
print(np.array(head).reshape(-1).tolist())
Lucas Vazquez
  • 1,456
  • 16
  • 20

2 Answers2

1

This is already available from the itertools module.

from itertools import chain

temp = [x for x in chain.from_iterable(head)]
# or just temp = list(chain.from_iterable(head))
chepner
  • 497,756
  • 71
  • 530
  • 681
1

A n-dimensional array is better than a list in some cases.

import numpy as np
x = np.array([[1, 2], [3, 4]]) 
print(x.reshape(-1))
print(x.reshape(-1).tolist())
R zu
  • 2,034
  • 12
  • 30
  • It's print `[1 2 3 4]` but I want `[1, 2, 3, 4]` – Lucas Vazquez Aug 13 '19 at 20:30
  • 1
    Conversion from list to numpy array is slow. Vectorized operations over numpy array is much faster than over a list. Pick the data structure/implementation that suits your use case. If you need lots of insertion/deletion operation, use list. – R zu Aug 13 '19 at 20:40