Merge the contents of two lists by considering the contents in Python?

Asked

Viewed 351 times

4

The scenario is this, I have two lists, ex:

 list1 = [1,2,3,4]
 list2 = [5,6,7,8]

I want to generate a new list that looks like this:

[15,26,37,48]

That is, to "join" the elements of each index. I did the concatenation like this, but the list went like this:

[1,5,2,6,3,7,4,8]

Could use join to get the way out I want? Both lists have the same size.

1 answer

3


Assuming that the values always have only one digit, one option is to do the math - the numbers in the first list correspond to the ten, and those in the second list correspond to the unit, so just multiply the first by 10 and add with the second:

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]

result = []
for n1, n2 in zip(list1, list2):
    result.append(10 * n1 + n2)

print(result) # [15, 26, 37, 48]

zip traverses both lists at the same time, then at each iteration of the for, n1 will be a number of list1 and n2 will be a number of list2.

The detail is that the loop is terminated when the smallest of the lists is finished, but as you said that both have the same size, this will not be a problem.

If you want, you can also use a comprehensilist on, much more succinct and pythonic:

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]

result = [ 10 * n1 + n2 for n1, n2 in zip(list1, list2) ]

print(result) # [15, 26, 37, 48]

join serves to join several strings into one, so it wouldn’t suit your case.

And probably someone will suggest turning the numbers into strings, concatenating them and turning them into numbers again. Something like this:

result = []
for n1, n2 in zip(list1, list2):
    result.append(int(str(n1) + str(n2)))

But I find a turn unnecessary. If lists only have numbers, I find it simpler to do the math instead of converting to string and then back to number.

  • 1

    Thanks! It worked here, I’m learning Python now, I didn’t know the zip or the term pythonic, more items for study :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.