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.
Thanks! It worked here, I’m learning Python now, I didn’t know the zip or the term pythonic, more items for study :)
– BARBARA