Merging sorted arrays in Python def merge_arrays(list1, list2):
  len_list1 = len(list1); len_list2 = len(list2)
  merge_len = len_list1 + len_list2
  merge_list = []

  l1_ptr = 0
  l2_ptr = 0
  # import pdb; pdb.set_trace()
  while(l1_ptr &lt;= len_list1-1 and l2_ptr &lt;= len_list2-1):

    if (list1[l1_ptr] &lt;= list2[l2_ptr]):
      merge_list.append(list1[l1_ptr])
      l1_ptr += 1
    
    elif (list1[l1_ptr] &gt; list2[l2_ptr]):
      merge_list.append(list2[l2_ptr])
      l2_ptr += 1
      
  if l1_ptr &gt; len_list1-1: #list1 exhausted
    for item in list2[l2_ptr:]:
      merge_list.append(item)
  else:
    for item in list1[l1_ptr:]:
      merge_list.append(item)

  return merge_list

I am trying to merge sorted arrays in python. How can I improve this? Honestly it looks like I've written this in C and not in Python
Use a 4-space indent.
Don't repeatedly subtract 1 from the same unchanging value.
Simplify the compare conditional: just use else.
Take advantage of list.extend().
Drop the wrap-up conditionals: they aren't actually needed. Code like zs.extend(xs[xi:]) will work fine even if xi exceeds the list
bounds.
Shorten the variable names to lighten the code weight and increase readability. There's no loss of meaning here, because all of the short names are quite conventional and make sense in a generic function like this.
def merge_arrays(xs, ys):
    # Setup.
    xmax = len(xs) - 1
    ymax = len(ys) - 1
    xi = 0
    yi = 0
    zs = []

    # Compare and merge.
    while xi &lt;= xmax and yi &lt;= ymax:
        if xs[xi] &lt;= ys[yi]:
            zs.append(xs[xi])
            xi += 1
        else:
            zs.append(ys[yi])
            yi += 1

    # Merge any remainders and return.
    zs.extend(ys[yi:])
    zs.extend(xs[xi:])
    return zs

Last night I wrote an iterator-base solution but somehow forgot that next()
supports a handy default argument: the code was awkward and Maarten
Fabré did a nicer
implementation. But if your willing to use
more_itertools.peekable()
you can achieve a simple, readable implementation. Thanks to
superb-rain
for an idea in the comments that helped me simplify further.
from more_itertools import peekable

def merge(xs, ys):
    xit = peekable(xs)
    yit = peekable(ys)
    while xit and yit:
        it = xit if xit.peek() &lt;= yit.peek() else yit
        yield next(it)
    yield from (xit or yit)