Home > Back-end >  Writing a function to merge 2 lists...maybe more
Writing a function to merge 2 lists...maybe more

Time:05-03

New to python... I am trying to write a function merge() to take two lists and combine them, and then I would like to expand that to an n number of lists.

The output I get from this code is only the grapes list and not concatenated with the apples list.

Failed Attempt with my fuction:

grapes = ['purple', 'red']
apples = ['green', 'yellow', 'orange']

def merge():
    ''' merge the lists '''
    for i in apples:
        grapes.append(i)
print("Concatenated list: "   str(grapes))

merge()

Output :

Concatenated list: ['purple', 'red']

Thank you for the read...

CodePudding user response:

You should first call merge() before outputing grapes

I mean :

grapes = ['purple', 'red']
apples = ['green', 'yellow', 'orange']

def merge():
    ''' merge the lists '''
    for i in apples:
        grapes.append(i)

merge()
print("Concatenated list: "   str(grapes))

Or you could just do:

fruits = grapes   apples
print(fruits)

CodePudding user response:

Use this

array1 = ["a" , "b" , "c" , "d"]
array = [1 , 2 , 3 , 4 , 5]

def merge(*array_list):
  output_array = []
  for array in array_list:
    output_array = output_array   array
  return output_array

merged_array = merge(array1 , array2)

Hope it helps :)

  • Related