Reputation: 439
it was really difficult to explain this in one sentence when I wrote a title. So, I'll jump to an example right away.
list1=[[1],[2],[3]]
list2=[['abc'],['def'],['ghi']]
a_list=[]
for i,j in zip(list1,list2):
a_list.append(i)
a_list.append(j)
print (a_list)
Acutal output:
[[1], ['abc'], [2], ['def'], [3], ['ghi']]
The above code gives me the above output.
But what I want to get is the below output.
Expected output:
[[1,'abc'], [2,'def'], [3,'ghi']]
I tried using extend but I guess it's not a matter of using append or extend. I think I'm missing one tiny part but could someone help me out?
Upvotes: 0
Views: 75
Reputation: 106891
You can join the sub-lists in a list comprehension instead:
[a + b for a, b in zip(list1, list2)]
or map the two lists to the list.__add__
method:
list(map(list.__add__, list1, list2))
Upvotes: 3
Reputation: 326
What you're doing is appending initial lists to the a_list
, not the values. What you need to do instead is to concatenate them and then append to the result like that:
for i,j in zip(list1,list2):
a_list.append(i + j)
Another solution would be to append a list that consists of the first items of each of the initial lists.
for i,j in zip(list1,list2):
a_list.append([i[0], j[0]])
Upvotes: 2
Reputation: 1406
This should solve it.
for i, j in zip(list1,list2):
a_list.append(i+j)
print (a_list)
[[1, 'abc'], [2, 'def'], [3, 'ghi']]
Upvotes: 1
Reputation: 602
You only need a single variable when iterating through zip
:
In [17]: for i in zip(list1, list2):
...: print(i)
...:
([1], ['abc'])
([2], ['def'])
([3], ['ghi'])
And then:
In [20]: for i in zip(list1, list2):
...: a_list.append(i)
In [21]: a_list
Out[21]: [([1], ['abc']), ([2], ['def']), ([3], ['ghi'])]
Since you are pulling two elements at a time, you are actually separating the elements and canceling the zip operation.
Upvotes: 1