192k views
1 vote
Given the lists list1 and list2, not necessarily of the same length, create a new list consisting of alternating elements of list1 and list2 (that is, the first element of list1 followed by the first element of list2 , followed by the second element of list1, followed by the second element of list2, and so on. Once the end of either list is reached, the remaining elements of the longer list is added to the end of the new list. For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6, 7, 8], then the new list should contain [1, 4, 2, 5, 3, 6, 7, 8]. Associate the new list with the variable list3.

User Kyberias
by
5.8k points

1 Answer

4 votes

Answer:

The following code is written in Python Programming Language.

Program:

list1=[1,2,3]

# initialized the list type variable

list2=[4,5,6,7,8]

# initialized the list type variable

list3=[]

# initialized the empty list type variable

for j in range(max(len(list1), len(list2))): #set for loop

if j<len(list1):

#set if statement

list3.append(list1[j])

#value of list1 appends in list3

if j<len(list2):

#set if statement

list3.append(list2[j])

#value of list2 append in list3

print(list3) #print the list of list3

Output:

[1, 4, 2, 5, 3, 6, 7, 8]

Explanation:

Here, we define three list type variables "list1", "list2", "list3" and we assign value in only first two variables "list1" to [1, 2, 3] and "list2" to [4, 5, 6, 7, 8] and third list is empty.

Then, we set the for loop and pass the condition inside it we pass two if conditions, in first one we compare the list1 from variable "j" inside it the value in list1 will append in list3, and in second one we compare "j" with list two and follow the same process.

After all, we print the list of the variable "list3".

User Jeff Beagley
by
5.1k points