Sam
Sam

Reputation: 11

Write a function that merges two lists, alternating elements from both lists. Python code

For example if a = [1, 4, 9, 16] and b = [9, 7, 4, 9, 11], the function returns a new list, result = [1, 9, 4, 7, 9, 4, 16, 9, 11]

This is the code I have so far.

def merge(a,b):
    mergedList =[]
    for i in range(len(a)):
        mergedList.append(a[i])
        mergedList.append(b[i])

def main():
    a = [1,4,9,16]
    b = [9,7,4,9,11]
    print("List a is", a)
    print("List b is", b)
    result = merge(a,b)
    print("The merged list is", result)
main()

The output I get is

List a is [1,4,9,16]
List b is [9,7,4,9,11]
The merged list is None

Does anyone know why the output for the new merged list is None?

Upvotes: 1

Views: 1574

Answers (1)

Ismail Hafeez
Ismail Hafeez

Reputation: 740

You have not returned the merged list. Therefore it's value is None. Change the first function to:

def merge(a,b):
    mergedList =[]
    for i in range(len(a)):
        mergedList.append(a[i])
        mergedList.append(b[i])
    return mergedlist

Upvotes: 1

Related Questions