Reputation: 3446
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
Upvotes: 3
Views: 2545
Reputation: 176938
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.
Upvotes: 4
Reputation: 149085
In your case, you should simply use extend
method :
list2.extend(list1)
Your lists are indeed 2d lists, but the result you want does not depend on that. So a simple extend
is enough.
Upvotes: 2
Reputation: 5347
('a','1')
in list1
is a single element
In [1]: list1 = [('a', '1'), ('b', '2'), ('c', '3')]
In [2]: list2 = [('d', '4'), ('e', '5'), ('f', '6')]
In [3]: for i in list1:
...: list2.append(i)
...:
In [4]: list2
Out[4]: [('d', '4'), ('e', '5'), ('f', '6'), ('a', '1'), ('b', '2'), ('c', '3')]
Upvotes: 0
Reputation: 174786
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')]
Upvotes: 4