0

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)]
4
  • 1
    Usually this operation would not be referred to as "concatenation". The concatenation of A and B would be A + B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Commented Oct 19, 2020 at 7:19
  • 1
    I would call this a good question. The problem is simple yes, but judging from the answers the zip function 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! Commented Oct 19, 2020 at 7:27
  • Does this answer your question? How to iterate through two lists in parallel? Commented Oct 19, 2020 at 7:33
  • By the way, these are all lists, not arrays Commented Oct 19, 2020 at 7:35

2 Answers 2

2

Use zip, the built-in for pairwise iteration:

C = list(zip(A, B))

Note that you are not concatenating the two lists.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your solution. But, the following solution resulted in C= [('1', '6'), ('2', '7'), ('3', '8'), ('4', '9'), ('5', '10')] which is not correct. I need C = [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
@PratheekHb this means you have a list of strings and not ints as you presented in the question...
Then your input was not what you showed in the question, but ['1', '2', '3', '4', '5'], etc. You can easily fix this: list(zip(map(int, A), map(int, B)))
0

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)]

4 Comments

Incorrect. 1. 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).
Corrected with range (misread history). The behavior if len(A) != len(B) has not been specified, so nothing wrong in that case.
Instructive solution. zip is, however, not more of a dependency than range or len. The are all just built-ins.
The following solution resulted in C= [('1', '6'), ('2', '7'), ('3', '8'), ('4', '9'), ('5', '10')] which is not correct. I need C = [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

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.