# How to combine/merge a number list and a string list into a new list in ascending order in python using recursion?

## Question:

I want to combine a number list and a string list

Example a = [1, 2, 3], b = [a, b, c, d]

combine a and b and the answer should be [1, a, 2, b, 3, c, d]

or a = [1,2,3], b = [b, d]

combine a and b and the answer should be [1, b, 2, d, 3]

``````def combine(a, b):
a = [str(int) for int in a]
b = [str(int) for int in b]
if a and b:
if a > b:
a, b = b, a
return [a] + combine(a[1:], b)
return a + b
``````

a = [1, 2, 3]
b = [‘a’, ‘b’, ‘c’, ‘d’]

combine(a, b)

But I got this

[‘1’, ‘2’, ‘3’, ‘a’, ‘b’, ‘c’, ‘d’]

``````a = [1, 2, 3]
b = ["a", "b", "c", "d"]
new = []
for i in range(max(len(a), len(b))):
if len(a) > i:
new.append(a[i])
if len(b) > i:
new.append(b[i])
``````

Are you looking to sort a, b, c… based on their position in the alphabet?

``````from string import ascii_lowercase
combined_list = [1, 2, 3] + ["a", "b", "c", "d"]
combined_list.sort(key=lambda elem: elem if type(elem) is int else ascii_lowercase.index(elem) + 1)
``````

If thats the case, maybe you want to consider creating your own sorting logic (1, "a", 2, "b"…) first and use that.

Used recursion:

``````def combine(nums, lets):
if not nums or not lets:
return nums + lets
res = []
counts = [0, 0]
num = nums
let = ord(lets) - 96
if num <= let:
counts += 1
res.append(nums)
if num >= let:
counts += 1
res.append(lets)
return res + combine(nums[counts:], lets[counts:])

if __name__ == '__main__':
nums = [1, 2, 3, 4]
lets = ['b', 'c', 'd']
print([str(i) for i in combine(nums, lets)])
``````
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.