Python code that combines two lists by taking elements alternately.
# e.g. [x,y,z], [101,102,103] → [x,101,y,102,z,103].
Python code implementation without user-defined functions & classes
Code:
#Python code that combines two lists by taking elements alternatingly ,
a = ["x", "y", "z"]
b = [101, 102, 103]
c = []
len_a = len(a)
len_b = len(b)
if len_a > len_b:
loop_times = len_a
else:
loop_times = len_b
for i in range(0, loop_times):
if i < len_a:
c.append(a[i])
if i < len_b:
c.append(b[i])
print(c)
Output:
['x', 101, 'y', 102, 'z', 103]
Python code implementation using function
Code:
#Python code that combines two lists by taking elements alternately using function
def combine_list_alternate_func(list_1, list_2):
c = []
len_a = len(list_1)
len_b = len(list_2)
if len_a > len_b:
loop_times = len_a
else:
loop_times = len_b
for i in range(0, loop_times):
if i < len_a:
c.append(list_1[i])
if i < len_b:
c.append(list_2[i])
return c
a = ["x", "y", "z"]
b = [101, 102, 103]
print(combine_list_alternate_func(a, b))
Output:
['x', 101, 'y', 102, 'z', 103]
Python code implementation using Classes
Code:
#Python code that combines two lists by taking elements alternately using class
class Combine_list_alternate_class(object):
def combine_list_alternate_func(self, list_1, list_2):
self.list_1 = list_1
self.list_2 = list_2
c = []
len_a = len(self.list_1)
len_b = len(self.list_2)
if len_a > len_b:
loop_times = len_a
else:
loop_times = len_b
for i in range(0, loop_times):
if i < len_a:
c.append(self.list_1[i])
if i < len_b:
c.append(self.list_2[i])
return c
a = ["x", "y", "z"]
b = [101, 102, 103]
#Creating Object
Object_1 = Combine_list_alternate_class()
#Calling function using created object
print(Object_1.combine_list_alternate_func(a, b))
Output:
['x', 101, 'y', 102, 'z', 103]
Enjoy Python Code By Pythonbaba 🙂