Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given the lists list1 and list2, not necessarily of the same length, create a ne

ID: 3765337 • Letter: G

Question

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, no additional elements are added. FOR EXAMPLE (DON'T USE THIS), 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]. Associate the new list with the variable  list3. (PYTHON: MY PROGRAMMING LAB)

Explanation / Answer

l1 = [1,2,3]
l2 = [4,5,6]

newl = []
for item1, item2 in zip(reversed(l1), reversed(l2)):
newl.append(item1)
newl.append(item2)

print newl

(OR)


I would do it with a list comprehension, rather than anything with len or range. e.g.:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zip(list1, list2)
[(1, 'a'), (2, 'b'), (3, 'c')]
[x for pair in zip(list1, list2) for x in pair]
[1, 'a', 2, 'b', 3, 'c']

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote