Table of Contents

Python Code that merges two sorted lists into a new sorted list.

# [1,4,6],[2,3,5] → [1,2,3,4,5,6].

Python code implementation without user-defined functions & classes

Code: 
#Python Code that merges two sorted lists into a new sorted list.


a = [1, 2, 3]
b = [4, 5, 6]
c = []
if a[0] < b[0]:
    c = a + b
else:
    c = b + a

print(c)

 

Output: 
[1, 2, 3, 4, 5, 6]

 

 

Python code implementation using function

Code: 
#Python Code that merges two sorted lists into a new sorted list using function.

def sort_two_list_func(list_a, list_b):
    c = []
    if list_a[0] < list_b[0]:
        c = list_a + list_b
        return c
    else:
        c = list_b + list_a
        return c

a = [1, 2, 3]
b = [4, 5, 6]

print(sort_two_list_func(a, b))

 

Output: 
[1, 2, 3, 4, 5, 6]

 

 

 

Python code implementation using Classes

Code: 
#Python Code that merges two sorted lists into a new sorted list using class.

class Sort_two_list_class(object):

    def sort_two_list_func(self, list_a, list_b):
        self.list_a = list_a
        self.list_b = list_b
        c = []
        if self.list_a[0] < self.list_b[0]:
            c = self.list_a + self.list_b
            return c
        else:
            c = self.list_b + self.list_a
            return c

a = [1, 2, 3]
b = [4, 5, 6]

#Create Object
Object_1 = Sort_two_list_class()

#Calling function using created Object
print(Object_1.sort_two_list_func(a, b))
Output: 
[1, 2, 3, 4, 5, 6]

 

 

 

 

 

Enjoy Python Code By Pythonbaba 🙂