I am new to Python and I would like to combine two arrays. I have two arrays: A and B and would like to get array C as follows:
A = [1, 2, 3, 4, 5]
B = [6, 7, 8, 9, 10]
Result array:
C = [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
Use zip, the built-in for pairwise iteration:
C = list(zip(A, B))
Note that you are not concatenating the two lists.
['1', '2', '3', '4', '5'], etc. You can easily fix this: list(zip(map(int, A), map(int, B)))Without any dependency:
>>> A = [1, 2, 3, 4, 5]
>>> B = [6, 7, 8, 9, 10]
>>> C = [(A[i], B[i]) for i in range(len(A))]
>>> C
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
len(A) is not an iterable. 2. If you change len(A) to range(len(A)), this approach will raise an IndexError if len(B) > len(A).len(A) != len(B) has not been specified, so nothing wrong in that case.zip is, however, not more of a dependency than range or len. The are all just built-ins.
A and Bwould beA + B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].zipfunction is not as widely used as it should be, so the question already had its merit. Additionally, because of the unconventional description of 'concatenation', googling for it would have never yielded the desired results. Furthermore it was well asked, provided a nicely formatted example and described it very well. That is well asked question, especially for a newcommer! Welcome to stackoverflow!