Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Appending a 2D list to another 2D list

I am trying to append a 2D list to another 2D list as follows:

list1 = [('a', '1'), ('b', '2'), ('c', '3')]
list2 = [('d', '4'), ('e', '5'), ('f', '6')]

If I append list1 to list2 should output:

list2 = [('d', '4'), ('e', '5'), ('f', '6'), ('a', '1'), ('b', '2'), ('c', '3')]

I have tried to solve the problem with the following code:

for x, y in list1:
    list2.append([x, y])

Which has given me the following error:

Traceback (most recent call last):
    File "C:\Python27\SortCounty.py", line 59, in <module>
        for x, y in final_list:
ValueError: too many values to unpack
like image 400
algorhythm Avatar asked Aug 29 '26 00:08

algorhythm


2 Answers

Simple, use + operator. You could concatenate two lists using + operator.

>>> list1 = [('a', '1'), ('b', '2'), ('c', '3')]
>>> list2 = [('d', '4'), ('e', '5'), ('f', '6')]
>>> list2 + list1
[('d', '4'), ('e', '5'), ('f', '6'), ('a', '1'), ('b', '2'), ('c', '3')]
like image 125
Avinash Raj Avatar answered Aug 31 '26 21:08

Avinash Raj


You can use extend to modify list2 inplace:

>>> list2.extend(list1)
>>> list2
[('d', '4'), ('e', '5'), ('f', '6'), ('a', '1'), ('b', '2'), ('c', '3')]

This is particularly efficient if you're extending a large list, since no copy of that list is made: the operation is O(k) in complexity, where k is the length of the list you're adding on.

This is essentially the same behaviour as the code in your question that, as others have pointed out, should work. In practice extend should be a little faster because the loop over list1 is moved down to C level.

ValueError: too many values to unpack indicates that one or more of the tuples in your list final_list has more than two elements. This causes the line for x, y in final_list: to raise the error since x and y can't label every element in the tuple.

like image 26
Alex Riley Avatar answered Aug 31 '26 20:08

Alex Riley