Could this code be improved?

is this the best way of doing it?
if not how can i improve it?

this returns the indices which match but before all that it checks which list is smaller and uses that as the range

def same_values(lst1,lst2):
  index = []
  length = range(len(lst1))
  length2 = range(len(lst2))
  
  
  if len(lst1) <= len(lst2):
    for i in length:
      if lst1[i] == lst2[i]:
        index.append(i)
    return index
  else:
    for i in length2:
      if lst1[i] == lst2[i]:
        index.append(i)
    return index
      

zipping the two lists resolves the uneven length concern by truncating the longer of the two lists. Values are paired up by their indices. 0:0, 1:1, 2:2, &c. Mind, the instructions do state two lists of numbers of equal size.

With a zipped list we only iterate a single object. Using enumerate we can track the index.

for i, x in enumerate(zip(lst1, lst2)):

x is a tuple, so we can unpack it…

    a, b = x
def same_values(lst1, lst2):
  y = []
  for i, x in enumerate(zip(lst1, lst2)):
    a, b = x
    if a == b:
      y.append(i)
  return y

The more naive approach is to keep track of the index with a count variable.

    count = 0
    y = []
    for x in zip(lst1, lst2):
        a, b = x
        if a == b:
            y.append{count)
        count += 1
    return y

We will most certainly come up with other naive approaches if one sticks with the problem awhile. Play it out and see how many you can come up with.

2 Likes