1

Let's suppose that I have 3 python two-dimensional lists (data_1, data_2, data_3) of 10x5 dimensions. I want to make one list (all_data) from them with 30x5 dimensions. For now, I am doing this by applying the following:

data_1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ..., [46, 47, 48, 49, 50]]
data_2 = [[101, 102, 103, 104, 105], [106, 107, 108, 109, 110], ..., [146, 147, 148, 149, 150]]
data_3 = [[201, 202, 203, 204, 205], [206, 207, 208, 209, 210], ..., [246, 247, 248, 249, 250]]
all_data = []
for index, item in enumerate(data_1):
    all_data.append(item)

for index, item in enumerate(data_2):
    all_data.append(item)

for index, item in enumerate(data_3):
    all_data.append(item)

If I simply do something like this:

all_data.append(data_1)
all_data.append(data_2)
all_data.append(data_3)

then I get a list of 3x10x5 which is not what I want.

So can I create a 30x5 list by appending three 10x5 lists without using any for loop?

Outcast
  • 4,967
  • 5
  • 44
  • 99

5 Answers5

7

You can just extend your list.

data = []
data.extend(d1)
data.extend(d2)
data.extend(d3)
jsmolka
  • 780
  • 6
  • 15
5

Simply write:

all_data = data_1 + data_2 + data_3

If you want to merge all the corresponding sublists of these lists, you can write:

# function that merges all sublists in single list
def flatten(l):
    return [el for subl in l for el in subl]

# zipped - is a list of tuples of corresponding items (our deep sublists) of all the lists
zipped = zip(data_1, data_3, data_3)

# merge tuples to get single list of rearranges sublists
all_data = flatten(zipped)
Nikolay Lebedev
  • 346
  • 1
  • 9
  • Thank you for your response but this produces a 10x15 list and not a 30x5 list from the initial lists... – Outcast Feb 26 '18 at 12:40
  • 1
    if `data_1` and `data_2` and `data_3` contains sublists, what dimension have `data_1`? And what dimension have it's sublist? – Nikolay Lebedev Feb 26 '18 at 12:51
  • Thank you for completing the question. I added an alternative option to my answer. But I think that you are somewhere wrong about the dimensions of the desired list. The first option should give a dimension of 30 * 5. – Nikolay Lebedev Feb 26 '18 at 13:20
  • Thank you for your correct response again (two upvotes). – Outcast Feb 26 '18 at 13:28
1

How about:

all_data = data_1 + data_2 + data_3
man0v
  • 654
  • 3
  • 13
0

This should work:

data=[]
data[len(data):] = data1
data[len(data):] = data2
data[len(data):] = data3
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
0

In case you don't mind it being lazy, you could also do

import itertools

all_data = itertools.chain(data1, data2, data3)
zsquare
  • 9,916
  • 6
  • 53
  • 87