0

I have two lists and want to merge them. At the moment I am using wo for loops but for sure there are more efficient ways and I do appreciate your help. These are my lists:

big_list=[[0.0, 4.0],[2.0, 5.0],[1.0, 1.0]]
small_list=[7.0, 9.0, 35.0]

both lists have the same lengths. In reality they are much more bigger. Then, I want concatenate the first sublist of the big_list with first value of small_list. Length of all sublists of big_list are the same and they are always 2. Then I go for the next following sublists and values to have:

[[0.0, 4.0, 7.0],[2.0, 5.0, 9.0],[1.0, 1.0, 35.0]]

I tried the following code but I think there are faster and more efficient way to do it:

first_list=[]
for i in range (len(big_list)):
    arrange=[matches[i], seg_lines[i]]
    first_list.append(arrange)
final_list=[]
for i in first_list:
    new=[i[0][0], i[0][1], i[1]]
    final_list.append(new)

in advance, I appreciate any help.

2 Answers 2

1

One loop is enough for this

final_list = []
for i in range(len(big_list)):
    temp = big_list[i][::]
    temp.append(small_list[i])
    final_list.append(temp)

Or

>>> [big_list[i] + [small_list[i]] for i in range(len(big_list))]
[[0.0, 4.0, 7.0], [2.0, 5.0, 9.0], [1.0, 1.0, 35.0]]
Sign up to request clarification or add additional context in comments.

Comments

1
big_list=[[0.0, 4.0],[2.0, 5.0],[1.0, 1.0]]
small_list=[7.0, 9.0, 35.0]

for i in range(len(big_list)):
    big_list[i].append(small_list[i])

assert big_list == [[0.0, 4.0, 7.0],[2.0, 5.0, 9.0],[1.0, 1.0, 35.0]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.