Ask Your Question
0

How can I iterate through two lists in Python simultaneously and duplicate the items?

asked 2021-12-03 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-03-27 23:00:00 +0000

devzero gravatar image

Assuming you have two lists of equal length, you can use the built-in zip() function to iterate through both lists simultaneously, then append each item to a new list twice:

list1 = [1, 2, 3, 4] list2 = ['a', 'b', 'c', 'd'] duplicated_list = [] for item1, item2 in zip(list1, list2): duplicated_list.append(item1) duplicated_list.append(item2) print(duplicated_list) 

Output:

[1, 'a', 2, 'b', 3, 'c', 4, 'd']

In this example, we create two lists list1 and list2, then iterate over both of them using zip(). In each iteration, we append the current value from list1 and list2 to the duplicated_list twice. Finally, we print duplicated_list which contains all the items from both original lists duplicated.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-03 11:00:00 +0000

Seen: 16 times

Last updated: Mar 27 '23